JS partial-application

本文介绍了一种函数式编程技巧——部分应用,并通过JavaScript代码示例展示了如何使用它来创建更灵活的功能组合。部分应用允许预先设定函数的部分参数,返回一个新的接受剩余参数的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* Title: Partial application
   Description: the process of fixing a number of arguments to a function, 
   producing another function of smaller arity
*/

var partialAny = (function(aps) {

    // This function will be returned as a result of the immediately 
    // invoked function expression and assigned to the `partialAny` var.
    function func(fn) {
        var argsOrig = aps.call(arguments, 1);
        return function() {
            var args = [],
            argsPartial = aps.call(arguments),
            i = 0;
            // Iterate over all the originally-spedicified arguments. If that
            // argument was the `partialAny._` placeholder, use the next just
            // passed-in argument, otherwise use the originally-specified 
            // argument.
            for (; i < argsOrig.length; i++) {
                args[i] = argsOrig[i] === func._ ? argsPartial.shift() : argsOrig[i];
            }

            // If any just-passed-in arguments remain, add them to the end.
            return fn.apply(this, args.concat(argsPartial));
        };
    }

    // This is used as the placeholder argument.
    func._ = {};

    return func;
})(Array.prototype.slice);

// Slightly more legitimate example
function hex(r, g, b) {
    return '#' + r + g + b;
}

var redMax = partialAny(hex, 'ff', partialAny._, partialAny._);
console.log(redMax('11', '22')); // "#ff1122"
// Because `_` is easier on the eyes than `partialAny._`, let's use
// that instead. This is, of course, entirely optional, and the name
// could just as well be `foo` or `PLACEHOLDER` instead of `_`.
var __ = partialAny._;

var greenMax = partialAny(hex, __, 'ff');
console.log(greenMax('33', '44'));

var blueMax = partialAny(hex, __, __, 'ff');
console.log(blueMax('55', '66'));

var magentaMax = partialAny(hex, 'ff', __, 'ff');
console.log(magentaMax('77'));

// reference
// http://msdn.microsoft.com/en-us/magazine/gg575560.aspx
参考 : https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/partial-application.html

转载于:https://my.oschina.net/i33/blog/144065

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值