实现一个add方法

28 阅读1分钟

描述:实现一个add方法,使计算结果能够满足以下预期:add(1)(2)(3) = 6,add(1,2,3)(4)()=10

const add = (...args) => {
  const illegal = args.filter((item) => typeof item !== "number")
  if (illegal.length) throw TypeError("illegal")
  const sum = args.reduce((pre, cur) => pre + cur, 0)
  return (...args1) => {
    const illegal1 = args1.filter((item) => typeof item !== "number")
    if (illegal1.length) throw TypeError("illegal")
    if (args1.length) {
      return add(sum, ...args1)
    } else {
      return sum
    }
  }
}