高阶函数片段

ary: 操作数组

创建一个最多接受n个参数的函数,多余的参数将被忽略

// 原代码
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => Math.max(...(x.slice(0, 2))))

// 函数柯里化:后面的参数传入前面return的函数继续执行
const ary = (fn, n) => (...args) => fn(...args.slice(0, n))
// 示例
const firstTwoMax = ary(Math.max, 2)
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)) // [6, 8, 10]

call

const call = (key, ...args) => context => context[key](...args)
// 实例
Promise.resolve([1, 2, 3])
    .then(call('map', x => 2 * x))
    .then(console.log)
// 实际代码:map方法实际上是Array的一个属性
console.log([1, 2, 3]['map'](x => 2 * x))
// bind不会立即执行,call和apply才会
const map = call.bind(null, 'map')
Promise.resolve([1, 2, 3])
    .then(map(x => 2 * x))
    .then(console.log)

参考

Last updated