How can I make var a = add(2)(3); //5 work?

后端 未结 28 2339
长发绾君心
长发绾君心 2020-11-27 14:11

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I\

相关标签:
28条回答
  • 2020-11-27 14:46

    This will handle both

    add(2,3) // 5
    

    or

    add(2)(3) // 5
    

    This is an ES6 curry example...

    const add = (a, b) => (b || b === 0) ? a + b : (b) => a + b;
    
    0 讨论(0)
  • 2020-11-27 14:46
        let add = (a, b) => b === undefined ? add.bind(null, a) : a + b;
        console.log(add(10, 5)); //15
        console.log(add(10)(5)); //15
    

    /* In the arrow function which returns a ternary expression, we explicitly check if the 2nd argument(b) is passed in or not b==="undefined" in both cases of add(a,b) and add(a)(b).

    1. if "undefined" in the case of add(a)(b) it uses "add.bind(null,a)", the "bind" method is associated with all functions(functions are objects) which creates a new function that is returned by the arrow function and passes in:
      • "null" for the first argument "the context its binding to which allows it to default to the window object"
      • "a" the second argument to be returned with the new function.
      • so when the new function is called at this point add(a)>>>(b) "b" is no longer undefined so the ternary switches to a+b.
    2. If not b==="undefined" in the case of add(a, b) the ternary switches to a+b */
    0 讨论(0)
  • 2020-11-27 14:48

    You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.

    var add = function(x) {
        return function(y) { return x + y; };
    }
    
    0 讨论(0)
  • 2020-11-27 14:49
    function add(x) {
        return function(y) {
            return x + y;
        };
    }
    

    Ah, the beauty of JavaScript

    This syntax is pretty neat as well

    function add(x) {
        return function(y) {
            if (typeof y !== 'undefined') {
                x = x + y;
                return arguments.callee;
            } else {
                return x;
            }
        };
    }
    add(1)(2)(3)(); //6
    add(1)(1)(1)(1)(1)(1)(); //6
    
    0 讨论(0)
  • 2020-11-27 14:49
    function add(a, b){
     return a && b ? a+b : function(c){return a+c;}
    }
    
    console.log(add(2, 3));
    console.log(add(2)(3));
    
    0 讨论(0)
  • 2020-11-27 14:50

    This is concept of currying in JS.
    Solution for your question is:

    function add(a) {
      return function(b) {
        return a + b;
      };
    }
    

    This can be also achieved using arrow function:

    let add = a => b => a + b;
    

    solution for add(1)(2)(5)(4)........(n)(); Using Recursion

    function add(a) {
      return function(b){
        return b ? add(a + b) : a;
      }
    }
    

    Using ES6 Arrow function Syntax:

    let add = a => b => b ? add(a + b) : a;
    
    0 讨论(0)
提交回复
热议问题