手写篇

0 阅读1分钟

// 手写防抖
function debounce(fn, delay) {
  if (typeof fn !== 'function') throw Error('')

  let timer = null

  return function (...agrs) {
    if (timer) clearTimeout(timer)

    timer = setTimeout(() => {
      fn.apply(this, agrs)
    }, delay)
  }
}

// 手写节流
function throttle(fn, delay) {
  let timer = null

  return function (...args) {
    if (timer) return

    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

// 手写promise all
Promise.myPromise = function (arr) {
  if (!Array.isArray(arr)) {
    throw Error('promiseArray is not a array')
  }

  return new Promise((resolve, reject) => {
    const promises = arr.map(promise => Promise.resolve(promise))

    const result = []
    let count = 0

    if (promises.length === 0) {
      resolve(result)
    }

    promises.forEach((item, index) => {
      item.then(res => {
        result[index] = res
        count++

        if (count === promises.length) {
          resolve(result)
        }
      }).catch(err => {
        reject(err)
      })
    })

  })
}


// 函数柯里化
function curry(fn) {
  const len = fn.length

  return function a(...args) {
    if (args.length >= len) {
      return fn.apply(this, args)
    }

    return function (...nextArgs) {
      return a.apply(this, [...args, ...nextArgs])
    }
  }
}