Just a curious question. I want to create a function can handle infinite "layer"? make add(2)(3), add(1)(2)(3)...(10) all works.
Any ideas?
Just a curious question. I want to create a function can handle infinite "layer"? make add(2)(3), add(1)(2)(3)...(10) all works.
Any ideas?
You can, with a slight catch. The return value must be a function that you can coerce to a number. Here's how:
function add (addend) {
'use strict'
const sum = (this || 0) + addend
const chain = add.bind(sum)
for (const prop of Object.getOwnPropertyNames(Number.prototype)) {
chain[prop] = Number.prototype[prop].bind(sum)
}
return chain
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
// convinced yet?
let four = add(4)
console.log(typeof four, four === 4)
// it's a function, not a number, so coerce to a primitive first
four = Number(four)
console.log(typeof four, four === 4)
add()
is a function that contains its context (this
) and all the Number.prototype
properties, including its Symbol.toPrimitive
property. In strict mode, the context behaves a lot more nicely, allowing you to define it as a primitive value like a number instead of defaulting to window
and coercing bound primitives to Object
s.