Day4.函数柯里化

260 阅读1分钟

题目:

实现一个函数func,func接收一个数字n为参数,返回一个函数add,add可以柯里化接收n个参数,当接收到的参数数字到达n时,返回n个数字之和

add = func(count)

console.log(add(2)(3)(4) )   // 9
console.log(add(2,3)(4))    // 9
console.log(add(2,3,4) )    // 9
console.log(add(2)(3,4) )    // 9

实现

function func(count) {
  let p = []
  return function getParamsAndSum(...rest) {
    p = p.concat(rest)
    if (p.length < count) {
      return getParamsAndSum
    } else {
      return p.reduce((index, next) => index + next)
    }
  }
}
debugger
var add = func(3)
console.log(add(1, 2, 3))