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

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

提交回复
热议问题