Function Currying in JavaScript

Source:http://tech.pro/tutorial/2011/functional-javascript-part-4-function-currying

Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed.

Function currying allows and encourages you to compartmentalize complex functionality into smaller and easier to reason about parts. These smaller units of logic are dramatically easier to understand and test, and then your application becomes a nice and clean composition of the smaller parts.

var sendMsg = function (from, to, msg) {
    alert(["Hello " + to + ",", msg, "Sincerely,", "- " + from].join("\n"));
};
var sendMsgCurried = curry(sendMsg); // returns function(a,b,c)
var sendMsgFromJohnToBob = sendMsgCurried("John")("Bob"); // returns function(c)
sendMsgFromJohnToBob("Come join the curry party!"); 
//=> "Hello Bob, Come join the curry party! Sincerely, - John"

If we know the number of arguments, we can do manual currying.

// uncurried
var example1 = function (a, b, c) {
    // do something with a, b, and c
};

// curried
var example2 = function(a) {
    return function (b) {
        return function (c) {
            // do something with a, b, and c
        };
    };
};

a simple helper function sub_curry

function sub_curry(fn /*, variable number of args */) {
    var args = [].slice.call(arguments, 1);
    return function () {
        return fn.apply(this, args.concat(toArray(arguments)));
    };
}

a complete curry function

function curry(fn, length) {
    // capture fn's # of parameters
    length = length || fn.length;
    return function () {
        if (arguments.length < length) {
            // not all arguments have been specified. Curry once more.
            var combined = [fn].concat(toArray(arguments));
            return length - arguments.length > 0 
                ? curry(sub_curry.apply(this, combined), length - arguments.length)
                : sub_curry.call(this, combined );
        } else {
            // all arguments have been specified, actually call function
            return fn.apply(this, arguments);
        }
    };
}

CodeWars - A Chain adding function

We want to create a function that will add numbers together when called in succession.

add(1)(2);
// returns 3

We also want to be able to continue to add numbers to our chain.

add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

and so on.

A single call should return the number passed in.

add(1) // 1

and we should be able to store the result and reuse it.

var addTwo = add(2);
addTwo // 2
addTwo(3) // 5
addTwo(3)(5) // 10

We can assume any number being passed in will be valid javascript number.

function add(n){
    var f = function(x){
        return add(n+x)
    }
    f.toString = function(){
        return n
    }
    return f
}

 

posted @ 2015-07-01 11:07  lilixu  阅读(990)  评论(0编辑  收藏  举报