Puzzle: JS Function that returns itself until there are no arguments

后端 未结 5 2067
北荒
北荒 2020-12-06 14:29

I\'m trying to solve a puzzle, and am at my wit\'s end trying to figure it out.

I\'m supposed to make a function that works like this:

add(1);                


        
5条回答
  •  我在风中等你
    2020-12-06 14:33

    Here's a variation using bind:

    var add = function _add(a, b) {
        var boundAdd = _add.bind(null, a + b);
    
        boundAdd.valueOf = function() { 
            return a + b; 
        }
    
        return boundAdd;
    }.bind(null, 0);
    

    We're taking advantage of a feature of bind that lets us set default arguments on the function we're binding to. From the docs:

    bind() also accepts leading default arguments to provide to the target function when the bound function is called.

    So, _add acts as a sort of master function which takes two parameters a and b. It returns a new function boundAdd which is created by binding the original _add function's a parameter to a + b; it also has an overridden valueOf function which returns a + b (the valueOf function was explained quite well in @RobG's answer).

    To get the initial add function, we bind _add's a parameter to 0.

    Then, when add(1) is called, a = 0 (from our initial bind call) and b = 1 (passed argument). It returns a new function where a = 1 (bound to a + b).

    If we then call that function with (2), that will set b = 2 and it'll return a new function where a = 3.

    If we then call that function with (3), that will set b = 3 and it'll return a new function where a = 6.

    And so on until valueOf is called, at which point it'll return a + b. Which, after add(1)(2)(3), would be 3 + 3.

提交回复
热议问题