mortal-cultivation-biography / daydayup

A FE interview-questions collection repo.
8 stars 0 forks source link

实现一个可以无限累加的函数 #32

Open nmsn opened 1 year ago

nmsn commented 1 year ago
const a = sum(1, 2, 3).valueOf() //6
const b = sum(2, 3)(2).valueOf() //7
const c = sum(1)(2)(3)(4).valueOf() //10
const d = sum(2)(4, 1)(2).valueOf() //9
const e = sum(1)(2)(3)(4)(5)(6).valueOf() // 21
nmsn commented 1 year ago
function sum (...args) {
  const f = (...rest) => sum(...args, ...rest)
  f.valueOf = () => args.reduce((x, y) => x + y, 0)
  return f
}