本两周总结

URL编码

escape()

用于js对字符串进行编码(不常用)

encodeURL

用于整个URL跳转

不能编码的符号A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( )

encodeURIComponent()

用于参数的传递

不能编码的符号A-Z a-z 0-9 - _ . ! ~ * ' ( )

最大子序和

动态规划dp

//最大和的连续子数组
const maxSubArray = nums => {
    let n = nums.length
    let dp = nums[0]
    let res = dp
    for (let i = 1; i < n; i++) {
        dp = Math.max(nums[i], dp + nums[i])
        //如果只有一个值
        res = Math.max(dp, res)
    }
    return res
}
console.log(maxSubArray([ 2, 3,10,1,-1,2,-1,-10]))

编码面试第六版

https://github.com/careercup/CtCI-6th-Edition-JavaScript

判断两个字符串是否相等

const checkPermute = (stringOne, stringTwo) => {
    if (stringOne.length !== stringTwo.length) {
        return false
    } else {
        let sortedStringOne = stringOne.split('').sort().join('')
        let sortedStringTwo = stringTwo.split('').sort().join('')
        return sortedStringOne === sortedStringTwo
    }
}
console.log(checkPermute('abc', 'cdg'))

'aabcccccaaa' a5b1c5

const objArr = str => str.split('').reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1
    return acc
}, {})
const ArrayObj = obj => Object.entries(obj).reduce((acc, val) => {
    acc += val[0] + val[1]
    return acc
}, '')
console.log(ArrayObj(objArr('aabcccccaaa')))
//a5b1c5

Math.max('',2)   //2   进行强转啦

const strComp = str => {
    //总数
    let res = '',
        b = '',
        bCount = '',
        maxCount = 1
    for (let i = 0; i < str.length; i++) {
        if (b !== str[i]) {
            res = res + b + bCount
            b = str[i]
            maxCount = Math.max(maxCount, bCount)
            bCount = 1
        } else {
            bCount++
        }
    }
    res = res + b + bCount
    return maxCount === 1 ? str : res
}
console.log(strComp('abaabb')) //a1b1a2b2
console.log(strComp('abc'))//abc

URI.js

const getType = value => {
    return String(Object.prototype.toString.call(value).slice(8, -1))
}

在两个整数之间得到随机整数

const getNum = num => typeof (num) === 'number' && num % 1 === 0 ? num : 0
const getRandomNumber = (min, max) => {
    min = getNum(min)
    max = getNum(max)
    return Math.floor(Math.random() * (max - min + 1) + min)
}

打印文件

const fs = require('fs')
let jokes = {}
jokes.allJokes = () => {
    let fileContents = fs.readFileSync('./test7.js', 'utf8')
    return fileContents.split(/
?
/)
}
console.log(jokes.allJokes())

模块化

require:   `node和es6`都支持引入
export/import: es6支持的导出引入
module.exports/exports :只有node支持

export 与 export default 均可用于导出常量,函数,文件,模块
一个文件或模块中,export ,import 可以有多个,export default 仅仅有一个
通过export 方式导出,在导入时要加{},export default 则不需要
export 能直接导出变量表达式,export default 不行

文件1
*导出
export function circumference(radius) {
  return 2 * Math.PI * radius;
}
export const getArticleByPath = (data) => {
  return fetch({
    url: '/api/help/contentTxtByPath',
    method: 'GET',
    params: data
  })
}
可以是多个

*导入
import {circumference } from './1.js';

文件2

导出
const add1 = (a, b) => a + b;
const odd = (a, b) => a - b;

export default {
  add1,
  odd
}

导入
import util from '../util/test1'
util.odd(10,20) //-10

import  '**' from 'vue'直接寻找的是依赖包里的文件

date-fns

toDate

function toDate(argument) {
    //如果不存在
    if (argument == null) {
        throw new TypeError('不存在就报错了')
    }
    let argStr = Object.prototype.toString.call(argument)
    if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') {
        // new Date()
        return new Date(argument.getTime())
    } else if (typeof argument === 'number' || argStr === '[object Number]') {
        // 12123313113 毫秒
        return new Date(argument)
    }
    //否则即使有问题的
    return new Date(NaN)
}

toInteger

const toInteger = (dirty) => {
  //+null 0   +true  1 +false  0
  if (dirty === null || dirty === true || dirty === false) {
    return NaN
  }
  let number = Number(dirty)
  // +undefined NaN
  if (isNaN(number)) {
    return number
  }
  return number<0?Math.ceil(number):Math.floor(number)
}

addLeadingZeros

function addLeadingZeros(number, targetLength) {
  var sign = number < 0 ? '-' : '';
  var output = Math.abs(number).toString();

  while (output.length < targetLength) {
    output = '0' + output;
  }

  return sign + output;
}

addLeadingZeros(-3, 4) // -0003

assign

console.log(Object.assign({}, {name: 'xxx'}))
const assign = (target, prop) => {
    if (target == null) {
        throw new Error('target  不能是null或者undefined')
    }
    prop = prop || {}
    for (let item in prop) {
        if (Reflect.has(prop, item)) {
            target[item] = prop[item]
        }
    }
    return target
}
console.log(assign({}, {name: 'xxx'}))

自执行函数

function addLeadingZeros(a,b) {
   return a+b
}

const add = () => {
//        return ( addLeadingZeros)(1, 3)
    return (0, addLeadingZeros)(1, 3)
}
console.log(add())
我看到很多源码写成这种,其实的目的是怕打包的时候出现错乱的问题

ramda.js

_map

const _map = (array, fn) => {
    let inx = -1
    let len = array.length
    let res = Array(len)
    while (++inx < len) {
        res[inx] = fn(array[inx])
    }
    return res;
}

//lodash
const _map = (array, fn) => {
  let inx = -1
  // let len = array.length
  let len = array == null ? 0 : array.length;
//  let res = Array(len)
  let res =new Array(len)
  while (++inx < len) {
    // res[inx] = fn(array[inx])
    res[inx] = fn(array[inx], inx, array)
  }
  return res;
}
console.log(_map(['1', '2', ''], val => +val))

some

const some = (list, item) => {
    let index = -1
    while (++index < list.length) {
        if (list[index] === item) {
            return true
        }
    }
    return false
}
console.log(some([1, 2, 3, 4], 3)) //true

path

const path = (array, obj) => {
    let val = obj
    let idx = -1
    while (++idx < array.length) {
        //跳出循环
        if (val == null) {
            return
        }
        val = val[array[idx]]
    }
    return val
}
console.log(path(['a', 'b'], {a: {b: 2}})) // 2
console.log(path(['a', 'b'], {c: {b: 2}}))// undefined

apertrue

const apertrue = (list, n) => {
    let a = Array.from({length: Math.ceil(list.length / n)}, v => [])
    return a.reduce((acc, val, index) => {
        acc[index] = list.slice(index * n, n * (index + 1))
        return acc
    }, [])
}
console.log(apertrue([1, 2, 3, 4, 5], 2))
//[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

const apertrue = (list, n) => {
    let index = -1
    // let idx=0;
    let limit = new Array(Math.ceil(list.length / n))
    while (++index < limit.length) {
        limit[index] = [].slice.call(list, index * n, (index + 1) * n)
        // limit[index] = [].slice.call(list, idx, idx+=n)
    }
    return limit
}
console.log(apertrue([1, 2, 3, 4, 5], 3))
// [ [ 1, 2, 3 ], [ 4, 5 ] ]

const apertrue = (list, n) => {
    return Array.from({
        length: Math.ceil(list.length / n)
    }, (val, index) => list.slice(index * n, n * (index + 1)))
}

const apertrue = (list, n) => {
  let idx = 0;
  return Array.from({
    length: Math.ceil(list.length / n)
  }, () => list.slice(idx, idx += n))
}

append

console.log(['write', 'more'].concat('tests'))
// [ 'write', 'more', 'tests' ]
console.log(['write', 'more'].concat(['tests']))
// [ 'write', 'more', 'tests' ]

mapValues

console.log(mapValue(val => val * 3, {a: 1, b: 2, c: 3}))
// { a: 3, b: 6, c: 9 }

const mapValue = (fn, obj) => {
    return Object.keys(obj).reduce((acc, val) => {
        acc[val] = fn(obj[val])
        return acc
    }, {})
}

chain

const duplicate = n => [n, n]
console.log(chain(duplicate, [1, 2, 3]))
// [ 1, 1, 2, 2, 3, 3 ]

const chain = (fn, array) => {
    return array.reduce((acc, val) => {
        return acc.concat(fn(val))
    }, [])
}

clamp

const clamp = (min, max, value) => {
    if (min > max) {
        throw new Error('哥,min比max大,报错了')
    }
    return value < min ? min : value > max ? max : value
}
console.log(clamp(1, 10, -1))
// 1
console.log(clamp(1, 10, 11))
// 10

type

const type = val => val === null ?
    'Null'
    : val === undefined ?
        'Undefined'
        : Object.prototype.toString.call(val).slice(8, -1)

slice

const slice = (list, start, end) => [].slice.call(list, start, end)

reverse

字符串/数组 倒序
const reverse = list => Array.isArray(list) ?
    [].slice.call(list, 0).reverse() :
    list.split('').reverse().join('')
console.log(reverse('abc'))
// cba
console.log(reverse(['a', 'b', 'c']))
// [ 'c', 'b', 'a' ]

nth

const nth = (offset, list) => {
    let idx = offset < 0 ? list.length + offset : offset
    return Array.isArray(list) ? list[idx] : list.charAt(idx)
}
console.log(nth(1, [1, 2, 3, 4, 5]))
//2
console.log(nth(-1, [1, 2, 3, 4, 5]))
//5
console.log(nth(-1, 'abcd'))
//d

includesWith

const includesWith = (fn, x, list) => {
    let idx = -1
    while (++idx < list.length) {
        if (fn(x, list[idx])) {
            return true
        }
    }
    return false
}
const eq = (a, b) => a === b
console.log(includesWith(eq, 2, [1, 2, 3, 4]))
//true

range

const isNumber = num => Object.prototype.toString.call(num) === '[object Number]';
const range = (from, to) => {
  if (!(isNumber(from) && isNumber(to))) {
    throw new TypeError('from to 都必须都有值')
  }
  let result = [];
  let n = from - 1;
  while (++n < to) {
    result.push(n)
  }
  return result
}
console.log(range(1, 10))

createThunk

const createThunk = (fn, ...fnArgs) => fn.apply(null, fnArgs);
console.log(createThunk((a, b) => a + b, 25, 26))
// 51

zipWith

const zipWith = (fn, a, b) => {
  let rv = [];
  let idx = -1;
  let len = Math.min(a.length, b.length)
  while (++idx < len) {
    rv[idx] = fn(a[idx], b[idx])
  }
  return rv
}
const add = (a, b) => a + b;
console.log(zipWith(add, [1, 2, 3], [4, 5, 6]))
// [ 5, 7, 9 ]

zipObj

const zipObj = (key, values) => {
  let idx = -1;
  let len = Math.min(key.length, values.length)
  let out = {};
  while (++idx < len) {
    out[key[idx]]=values[idx]
  }
  return out
}
console.log(zipObj(['a', 'b', 'c'], [1, 2, 3]))
//=> {a: 1, b: 2, c: 3}

zip

const zip = (a, b) => {
  let rv = [];
  let idx = -1;
  let len = Math.min(a.length, b.length)
  while (++idx < len) {
    rv[idx] = [a[idx], b[idx]]
  }
  return rv
}
console.log(zip(['a', 'b', 'c'], [1, 2, 3]))
// [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]

xprod 组合

const xprod = (a, b) => {
  let i = -1;
  let j;
  let ilen = a.length;
  let jlen = b.length;
  let result = [];
  while (++i < ilen) {
    j = -1;
    while (++j < jlen) {
      result[result.length] = [a[i], b[j]]
    }
  }
  return result;
}
console.log(xprod([1, 2], ['a', 'b']))
//=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

adjust

const adjust = (idx, fn, list) => {
  if (idx >= list.length || idx < -list.length) {
    //索引大于长度或者小于-长度
    return list;
  }
  let _idx = idx < 0 ? list.length +idx : idx;
  let _list = list.slice();
  _list[_idx] = fn(list[_idx]);
  return _list;
}
const add=val=>val.toUpperCase();
console.log(adjust(1, add, ['a', 'b', 'c', 'd']))
//[ 'a', 'B', 'c', 'd' ]
console.log(adjust(-1, add, ['a', 'b', 'c', 'd']))
//[ 'a', 'b', 'c', 'D' ]
console.log(adjust(-100, add, ['a', 'b', 'c', 'd']))
//[ 'a', 'b', 'c', 'd' ]

_concat

//合并两个数组
const _concant = (set1 = [], set2 = []) => {
  let len1 = set1.length;
  let len2 = set2.length;
  let idx;
  let result = [];
  idx = -1;
  while (++idx < len1) {
    result[result.length] = set1[idx]
  }
  idx=-1;
  while (++idx < len2) {
    result[result.length] = set2[idx]
  }
  return result
}
console.log(_concant([1, 2, 3, 4], [5, 6, 7, 8]))
// [ 1, 2, 3, 4, 5, 6, 7, 8 ]

_has

let obj = {
  name: 'xxx',
  age: 12
}
console.log(obj.hasOwnProperty('name'))
//true
console.log(Reflect.has(obj, 'name'))
//true
const _has = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
console.log(_has(obj, 'age'))
//true

_objectIs

//Object.is
const _objectIs = (a, b) => {
  if (a === b) {
    //+0!=-0
    return a !== 0 || 1 / a === 1 / b;
  } else {
    // NaN==NaN
    return a !== a && b !== b
  }
}
console.log(_objectIs(NaN, NaN))
//true
console.log(_objectIs(0, -0))
//false

正则趣事

`[Function: add]`
console.log('[Function: add]'.match(/Function: (w*)/)) //拿到分组的内容
// add

uniqWith

const uniqWith = (fn, list) => {
  let idx = -1;
  let len = list.length;
  let result = [];
  let item;
  while (++idx < len) {
    item = list[idx]
    if ((!result.includes(item)) && fn(item)) {
      result[result.length] = item;
    }
  }
  return result
}

console.log(uniqWith(val => typeof (val) !== 'string', ['1', '2', 3, 1, 2, 2]))
// [ 3, 1, 2 ]

arrayReduce

const arrayReduce = (fn, acc, list) => {
  let idx = -1;
  while (++idx < list.length) {
    acc = (fn)(acc, list[idx])
  }
  return acc
}
console.log(arrayReduce((a, b) => a + b, 0, [1, 2, 3, 4, 5]))
//15
console.log(arrayReduce((a, b) => (a[b] = String(b),a), {}, [1, 'a', 'b', 'c']))
//{ '1': '1', a: 'a', b: 'b', c: 'c' }

iota

function iota(n) {
  let result = [];
  let idx = -1;
  while (++idx < n) {
    result[result.length]=idx
  }
  return result
}
console.log(iota(10))
// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

lodash

filter

const filter = (array, fn) => {
  let index = -1;
  let resIndex = 0;
  let result = [];
  while (++index < array.length) {
    if (fn(array[index], index, array)) {
      result[resIndex++] = array[index]
    }
  }
  return result;
}
console.log(filter([1, 2, 3, 4], val => val % 2 == 0))
//[ 2, 4 ]

getTag

完善类型

const getTag = value => {
if (value == null) {
return value === undefined ? '[object Undefined]' : '[object Null]'
}
return Object.prototype.toString.call(value)
}

isSymbol

const isSymbol = value => {
  const type = typeof value;
  //是对象不是null
  return type == 'symbol' || (type === 'object' && value != null && getTag(value) === '[object Symbol]')
}
console.log(isSymbol(Symbol.iterator))
//true

baseToNumber

判断是否数字,不是转成NaN,但是如果是Symbol(Symbol.iterator)类型,+Symbol会报错
const baseToNumber = value => {
  if (typeof value === 'number') {
    return value
  }
  if (isSymbol(value)) {
      //难道 0/0 比NaN快
    return 0/0
  }
  return +value
}

after

//等执行几次后,执行
const after = (n = 0, func) => {
  if (typeof func !== 'function') {
    throw new TypeError('第二个参数必须是函数')
  }
  return (...args) => (--n < 1)? func.apply(null, args):undefined;
}
let a = after(3, (a, b) => a + b)
console.log(a(1, 2))//undefined
console.log(a(1, 2))//undefined
console.log(a(1, 2))//3
console.log(a(1, 2))//3

isObjectLike

//判断是不是对象,且不能为null
function isObjectLike(value) {
  return typeof value === 'object' && value !== null
}

before

const before = (n, func) => {
  return (...args) => {
    return (--n > -1) ? func.apply(null, args) : undefined;
  }
}
let a=before(2,(a,b)=>(a+b))
console.log(a(1, 2)) //3
console.log(a(1, 2)) //3
console.log(a(1, 2)) //undefined

isObject

function isObject(value) {
  const type = typeof value
  return value != null && (type === 'object' || type === 'function')
}

compact

const compact = array => {
  let result = [];
  if (array == null) {
    return result
  }
  for (let item of array) {
    if (item) {
      result[result.length] = item
    }
  }
  return result
}
let arr=['a', '', false, NaN, undefined, 1, 2, 3]
console.log(compact(arr))
console.log(arr.filter(Boolean))
//[ 'a', 1, 2, 3 ]

最大子数组

//动态规划
const maxSubArr = arr => {
  let len = arr.length;
  let sum = arr[0];
  for (let i = 1; i < len; i++) {
    sum = Math.max(sum + arr[i], arr[i])
  }
  return sum
}
let arr = [2, -2, 3, 5, -1, -1, 2, 1]
console.log(maxSubArr(arr))
// 9

dfs 字符串问题

const code = (s) => {
  let index = -1;
  const help = () => {
    let word = '';
    let count = 0;
    while (++index < s.length) {
      let ch = s[index];
      if (ch === '[') {
        word += help()
          .repeat(count)
        count = 0;
      } else if (ch === ']') {
        break;
      } else if (ch >= '0' && ch <= '9') {
        count = count * 10 + ch;
      } else {
        word += ch;
      }
    }
    return word
  }
  return help()
}
console.log(code('3[abc]2[der]'))
// abcabcabcderder
/* s = "3[a]2[bc]", return "aaabcbc".
 * s = "3[a2[c]]", return "accaccacc".
 * s = "2[abc]3[cd]ef", return "abcabccdcdcdef".*/

leetcode

https://github.com/lessfish/leetcode

粒子引擎

http://a-jie.github.io/Proton/#example
原文地址:https://www.cnblogs.com/fangdongdemao/p/11670264.html