柯里化的存在意义是什么

发布时间 2023-05-23 18:25:08作者: 10后程序员劝退师

柯里化的存在意义是什么?

在函数式编程中,我们其实往往希望一个函数处理的问题尽可能的单一,而不是将一大堆的处理过程交给一个函数来处理

我们是否就可以将每次传入的参数在单一的函数中进行处理,处理完后在下一个函数中再处理后的结果

// 支持多参数传递
function progressCurrying(func) {
    var args = Array.prototype.slice.call(arguments, 1);
    var _this = this
    
    return function() {
        var curArgs = Array.from(arguments)
        var totalArgs = args.concat(curArgs)

        // 如果参数个数小于最初的fn.length,则递归调用,继续收集参数
        if (totalArgs.length >= func.length) {
            return func.apply(null, totalArgs);
        } else {
            //参数不够,则递归调用,继续收集参数
            totatlArgs.unshift(func);
            return _this.progressCurrying.apply(_this, totatlArgs)
        }
    }
}

function add (x,y,z) {
  //return [].reduce.call(arguments, (a, b) => a + b)
    return x+y+z
}

const g = progressCurrying(add,'我','今年')

g('12岁')  //'我今年12岁'

 延展运用

function curry(fn) {
    // 缓存除第一个参数的所有参数
    let args = [].slice.call(arguments, 1);
    let _fn = function () {
        if (arguments.length === 0) {
            return fn.apply(this, args)
        } else {
            args.push(...arguments);
            return _fn
        }
    }
    return _fn
}
function add() {
    return [].reduce.call(arguments, (a, b) => a + b)
}
console.log(curry(add, 2)(1, 3, 4)(2, 3)(3)(4, 6)(7, 98)()) // 133