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

后端 未结 28 2336
长发绾君心
长发绾君心 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:57

    function add() { var sum = 0;

        function add() {
            for (var i=0; i<arguments.length; i++) {
                sum += Number(arguments[i]);
            }
            return add;
        }
        add.valueOf = function valueOf(){
            return parseInt(sum);
        };
        return add.apply(null,arguments);
    }
    
    // ...
    
    console.log(add() + 0);               // 0
    console.log(add(1) + 0);/*                 // 1
    console.log(add(1,2) + 0);               // 3
    
    0 讨论(0)
  • 2020-11-27 14:57
    let total = 0;
    const add = (n) => {
    if (n) {
        total += n;
        return add;
     }
    }
    
    add(1)(2)(3);
    console.log(total);
    

    Is this wrong?

    0 讨论(0)
  • 2020-11-27 14:59
    function add(n) {
      sum = n;
      const proxy = new Proxy(function a () {}, {
        get (obj, key) {
          return () => sum;
        },
        apply (receiver, ...args) {
          sum += args[1][0];
          return proxy;
        },
      });
      return proxy
    }
    

    Works for everything and doesn't need the final () at the end of the function like some other solutions.

    console.log(add(1)(2)(3)(10));    // 16
    console.log(add(10)(10));         // 20
    
    0 讨论(0)
  • 2020-11-27 15:00

    Arrow functions undoubtedly make it pretty simple to get the required result:

    const Sum = a => b => b ? Sum( a + b ) : a;
    
    console.log(Sum(3)(4)(2)(5)()); //14
    
    console.log(Sum(3)(4)(1)()); //8
    
    0 讨论(0)
  • 2020-11-27 15:01

    Here we use concept of closure where all the functions called inside main function iter refer and udpate x as they have closure over it. no matter how long the loop goes , till last function , have access to x.

    function iter(x){    
    return function innfunc(y){
    //if y is not undefined
    if(y){
    //closure over ancestor's x
    x = y+x;
    return innfunc;
    }
    else{
    //closure over ancestor's x
    return x;
        }
      }
    }
    

    iter(2)(3)(4)() //9 iter(1)(3)(4)(5)() //13

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

    we can do this work using closure.

        function add(param1){
          return function add1(param2){
          return param2 = param1 + param2;
        }
      }
      console.log(add(2)(3));//5
    
    0 讨论(0)
提交回复
热议问题