拒绝做API的搬运工,手写实现API

149 阅读1分钟

Array.prototype.reduce()

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。 reduce使用语法:

arr.reduce(callback(previousValue, currentValue[, index[, array]])[, initialValue])

简要介绍:

  • reduce 方法的第一个参数(callback)是核心,它对数组的每一项进行“叠加加工”,其最后一次的返回值将作为reduce方法的最终返回值。callback方法包含以下4个参数。
    1. previousValue 表示callback函数上一次的返回值。
    2. currentValue 表示数组遍历中正在处理的元素。
    3. index 可选参数,表示数组中正在处理的当前元素的索引。如果提供了initialValue,则起始索引为0,否则索引从1起始。
    4. array 可选参数,调用reduce()的数组。
  • initialValue 可选参数,作为第一次调用callback函数时的第一个参数。如果没有提供initialValue,那么数组中的第一个元素将作为callback函数的第一个参数。在没有初始值的空数组上调用 reduce 将报错。

通过reduce实现runPromiseInSequence

典型应用,按顺序执行Promise,代码如下:

const runPromiseInSequence = (array, value) => array.reduce(
    (promsieChain, currentFunction) => promsieChain.then(currentFunction),
    Promise.resolve(value)
)
// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}
// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}   
// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
  return a * 3
}
// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}
const array = [p1, p2, f3, p4]
runPromiseInSequence(array, 10).then(console.log) // 1200

实现一个reduce

Array.prototype.reduce = function(fun, initialValue) {
    let array = this
    let base = typeof initialValue === 'undefined' ? array[0] : initialValue
    let startPoint = typeof initialValue === 'undefined' ? 1 : 0
    array.slice(startPoint).forEach((val, index) => {
        base = fun(base, val, index + startPoint, array)
    })
    return base
}
// 求和
let array = Array(1,2,3,4,5)
let sum = array.reduce((previousValue, currentValue, index, array) => {
    return previousValue + currentValue
}, 0)
sum // 15