Skip to content
On this page

函数柯里化

js
function add() {
    let sum = 0
    let fn  = (...args) => {
        args.forEach(i => sum += i)
        return fn
    }
    fn.toString = () => sum
    return fn(...arguments)
}
 
console.log(add(1)(2)(3) == 6)
console.log(add(1, 2, 3) == 6)
console.log(add(1, 2)(3) == 6)
console.log(add(1)(2, 3) == 6)
function add() {
    let sum = 0
    let fn  = (...args) => {
        args.forEach(i => sum += i)
        return fn
    }
    fn.toString = () => sum
    return fn(...arguments)
}
 
console.log(add(1)(2)(3) == 6)
console.log(add(1, 2, 3) == 6)
console.log(add(1, 2)(3) == 6)
console.log(add(1)(2, 3) == 6)