函数柯里化的简单实现和应用

柯里化函数实现:

1. 使用函数的length+arguments+apply的相关知识

var slice = Array.prototype.slice
var curry = function (fn) {
    // 拿到fn参数之后的参数
    var args = slice.call(arguments, 1)
    return _curry.apply(this, [fn, fn.length].concat(args))
}

function _curry(fn, len) {
    // 获取fn, len之外的其他参数
    var oArgs = slice.call(arguments, 2);
    return function () {
        var args = oArgs.concat(slice.call(arguments))
        if (args.length >= len) {
            return fn.apply(this, args)
        }
        else {
            return _curry.apply(this, [fn, len].concat(args))
        }
    }
}

2. 使用函数的length + 扩展运算符...  + apply的知识:

var curry = function (fn, ...arg1) {
    const len = fn.length
    return _curry.apply(this, [fn, len, ...arg1])
}

function _curry(fn, len, ...rest1) {
    return function (...rest2) {
        var args = [...rest1, ...rest2]
        if (args.length >= len) {
            return fn.apply(this, args)
        }
        else {
            return _curry.apply(this, [fn, len].concat(args))
        }
    }
}

测试计算总和的功能:

function calcSum(num1, num2, num3) {
    return num1 + num2 + num3
}

var calcSum2 = function (...args) {
    // const arr = Array.from(arguments);
    const arr = Array.prototype.slice.call(arguments, 0);
    // const arr = Array.of(...args);
    let sum = 0;
    return arr.reduce((obj, cur) => {
        sum = obj + cur
        return sum
    }, sum)
}

const log = console.log
var len1 = 1
var calcSumCurry = _curry(calcSum2, 4)
log(calcSumCurry(3, 4, 5, 6))// 18
log(calcSumCurry(3)(4)(5)(6))//18
log(calcSumCurry(3)(4, 5)(6))//18

var calcSumCurry = curry(calcSum, 3)
log(calcSumCurry(4, 5))//12 
log(calcSumCurry(4)(5))//12

你可能感兴趣的:(JavaScript面试问题,闭包,函数的高级应用,javascript,前端,函数)