实现函数柯里化curry

317 阅读1分钟
  • 之前面试遇到一个题目, 使用 js 实现 add(1)(2)(3)(4) 返回 10, 当时在面试的时候都懵逼了, 于是在后面学习的时候专门学习一下, 下面上代码
    function curry(fn) {
        const g = (...args) => {
            if (args.length >= fn.length) {
                return fn(...args)
            }
            
            return (...left) => g(...args, ...left)
        
        }
        
        return g;
    }
    
    const add = (a,b,c) => a+b+c;
    
    const _add = curry(add);
    
    console.log(_add(1,2,3,4))
    console.log(_add(1)(2)(3)(4))
    console.log(_add(1,2)(3,4))
    console.log(_add(1,2,3)(4))

最终的结果都会返回10