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

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

    This question has motivated so many answers already that my "two pennies worth" will surely not spoil things.

    I was amazed by the multitude of approaches and variations that I tried to put "my favourite" features, i. e. the ones that I would like to find in such a currying function together, using some ES6 notation:

    const add=(...n)=>{
     const vsum=(a,c)=>a+c;
     n=n.reduce(vsum,0);
     const fn=(...x)=>add(n+x.reduce(vsum,0));
     fn.toString=()=>n; 
     return fn;
    }
    
    let w=add(2,1); // = 3
    console.log(w()) // 3
    console.log(w); // 3
    console.log(w(6)(2,3)(4)); // 18
    console.log(w(5,3)); // 11
    console.log(add(2)-1); // 1
    console.log(add()); // 0
    console.log(add(5,7,9)(w)); // 24
    .as-console-wrapper {max-height:100% !important; top:0%}

    Basically, nothing in this recursively programmed function is new. But it does work with all possible combinations of arguments mentioned in any of the answers above and won't need an "empty arguments list" at the end.

    You can use as many arguments in as many currying levels you want and the result will be another function that can be reused for the same purpose. I used a little "trick" to also get a numeric value "at the same time": I redefined the .toString() function of the inner function fn! This method will be called by Javascript whenever the function is used without an arguments list and "some value is expected". Technically it is a "hack" as it will not return a string but a number, but it will work in a way that is in most cases the "desired" way. Give it a spin!

提交回复
热议问题