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

后端 未结 28 2338
长发绾君心
长发绾君心 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 15:02
    function add(x){
      return function(y){
        return x+y
      }
    }
    

    First-class functions and closures do the job.

    0 讨论(0)
  • 2020-11-27 15:03

    ES6 syntax makes this nice and simple:

    const add = (a, b) => a + b;
    
    console.log(add(2, 5)); 
    // output: 7
    
    const add2 = a => b => a + b;
    
    console.log(add2(2)(5));
    // output: 7
    
    0 讨论(0)
  • 2020-11-27 15:04

    I came up with nice solution with closure, inner function have access to parent function's parameter access and store in its lexical scope, when ever we execute it, will get answer

        const Sum = function (a) {
            return function (b) {
                return b ? Sum(a + b) : a;
            }
        };
    
        Sum(1)(2)(3)(4)(5)(6)(7)() // result is 28
        Sum(3)(4)(5)() // result is 12
        Sum(12)(10)(20) // result is 42
    

    enter image description here

    0 讨论(0)
  • 2020-11-27 15:05
    const add = a => b => b ? add(a+b) : a;
    
    console.log(add(1)(2)(3)());
    

    Or (`${a} ${b}`) for strings.

    0 讨论(0)
提交回复
热议问题