user1249791
user1249791

Reputation: 1271

javascript partial function, arguments

I am trying to understand partial functions. I found this example (http://blog.thesoftwarecraft.com/2013/05/partial-functions-in-javascript.html) and I am unable to understand completely.

function partial(f) {
    console.log(f) // tip(p,check)
    var args = Array.prototype.slice.call(arguments, 1); //0.2

    var test_args = Array.prototype.slice.call(arguments);
    console.warn(test_args) // [tip(p,check), 0.2]

    return function () {
        console.warn(arguments) //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ...
        //where do these arguments come from? why don't appear at test_args?

        var other_args = Array.prototype.slice.call(arguments); //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ...

        console.log(args.concat(other_args)) // added percentage to array[0.2, 120, 0, [120, 90, 180]]

        return f.apply(null, args.concat(other_args)); //we execute tip with all the arguments (only 2 first will be used)
    }
}

function tip(percentage, check) {
    return check * percentage
}

[120, 90, 180].map(partial(tip, 0.2)); //[24, 18, 36]

Upvotes: 0

Views: 1874

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

In programming languages theory this is known as partial application. It basically takes your function that requires n arguments and n-k arguments and returns a function that has k arguments by partially applying these provided n-k arguments.

Take this example in a pseudo code

function mul(x, y)
    return x*y

function mul2(y)
    return function (x) mul(x, y)

mul(2, 3); // 6
var f = mul2(4); // returns a function
f(5); // 20

Although the function takes 2 arguments (n), you can make another function out of it by applying only 1 argument (n-k). The new function will then require only one argument (k).

Your partial takes a function and its arguments. It stores these arguments in the args variable. Then it returns the inner function that itself takes its arguments but since it has to combine the n-k arguments from the top level function with k arguments of the inner function, you have concat and the full list is passed to the original function.

Edit: as Andreas points in the comment, this is not called currying. The rest of the answer still holds though.

Upvotes: 0

Bergi
Bergi

Reputation: 664385

return function () {
     console.warn(arguments) //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ...

where do these arguments come from? why don't appear at test_args?

Because it's a new function - the returned one - which has a new arguments object. You can check here:

var tipper = partial(tip,0.2);
[120, 90, 180].map(function(el) {
     console.log(arguments); // here they are!
     return tipper(el);
});

Upvotes: 0

Related Questions