JS手写

114 阅读1分钟

flat

    function myFlat(n) {
      n = n ? n : Infinity;
      let arr = this;
      return getFlat(arr, n);

      function getFlat(arr, n) {
        let newArray = [];

        for (let i = 0; i < arr.length; i++) {
          if (Array.isArray(arr[i]) && n > 0) {
              newArray.push(...getFlat(arr[i], n - 1));
          } else {
            newArray.push(arr[i]);
          }
        }

        return newArray;
      }
    }
    Array.prototype.myFlat = myFlat;

深拷贝

function deepClone(obj, map = new WeakMap()){
      if(map.get(obj)){
        console.log(obj)
        return obj
      }
      let type = Object.prototype.toString.call(obj).slice(8,-1).toLowerCase()
      if(type === 'date') return new Date(obj)
      if(type === 'regexp') return new RegExp(obj)
      if(type === 'function') return obj.bind({})
      if(type === 'object' || type === 'array'){
        map.set(obj, true)
        let cloneObj = type === 'object' ? {} : []
        for(let key in obj){
          if(obj.hasOwnProperty(key)){
            cloneObj[key] = deepClone(obj[key])
          }
        }
        return cloneObj
      }
      return obj
    }

数组去重

function unique(arr){
      let res = arr.filter((item, index) => arr.indexOf(item) === index)
      return res
    }
    
  // new Set(arr)

reduce

Array.prototype.reduce2 = function(callback, initialValue){
      if(this === null){
        throw new TypeError('this is null or undefined')
      }
      if(typeof callback !== 'function'){
        throw new TypeError(callback +'is not a function')
      }
      let o = Object(this)
      let len = o.length >>> 0
      let accumulator = initialValue
      let k = 0, acc
      if(accumulator !== undefined){
        acc = initialValue
      } else {
        while(k < len && !(k in o)){
          k++
        }
        if(k >= len){
          throw new TypeError('Reduce of empty array with no initial value')
        }
        acc = o[k++]
      }
      while(k<len){
        if(k in o){
          acc = callback(acc, o[k],k,o)
        }
        k++
      }
      return acc
    }

函数柯里化

function curry(fn){
    return function judge(...args){
        if(args.length === fn) return fn(...args)
        return (...arg) => judge(...arg, ...args)
    }
}
function add(a, b, c) {
    return a + b + c
}
add(1, 2, 3)
let addCurry = curry(add)
addCurry(1)(2)(3)

new

function newOperate(fun, ...arg){
    if(typeof fun !== 'function') throw new TypeError(fun + ' is not a function')
    const obj = Object.create(fun.prototype)
    const res = fun.apply(obj, arg)
    if((typeof res === 'object' && fun !== null) || typeof res === 'function') return res
    return obj
}

instanceof

function myInstanceof(obj, func){
     if(typeof obj !== 'object' || obj === null) return false
      while(obj.__proto__ !== null){
        if(obj.constructor === func) return true
        obj = obj.__proto__
      }
      return false
   }

Promise.allSettled

Promise.allSetttled = function(promiseArr){
    return new Promise((resolve, reject) => {
      let res = []
      let num = 0
      promiseArr.forEach((item, index) => {
        Promise.resolve(item).then(value => {
          res[index] = ({ status: 'fulfilled', value})
          num++
          if(num === promiseArr.length) resolve(res)
        }, err => {
          res[index] = ({ status: 'rejected', err})
          num++
          if(num === promiseArr.length) resolve(res)
        })
      })

    })
  }

Promise.any

Promise.any = function(promiseArr){
    return new Promise((resolve, reject) => {
      let num = 0
      promiseArr.forEach(item => {
        Promise.resolve(item).then(value => {
          resolve(value)
        },
        err => {
          num++
          if(num === promiseArr.length){
            reject(new AggregateError('All promise were rejected'))
          }
        })
      })
    })
  }