Writing a javascript function in curry, which can be called an arbitrary number of times, which returns a value on the most recent function call

I am currently working on a programming problem when I ask that I create a javascript function that can be called this way.

add(1) // 1 add(1)(2) // 3 add(1)(2)(3); // 6 add(1)(2)(3)(4); // 10 add(1)(2)(3)(4)(5); // 15 

I am having trouble figuring out how to return a value on the last call.

For example, in order for add(1)(2) work, then add(1) must return a function, but in accordance with add(1) instructions, when the caller itself returns 1 .

I suggest that you can overcome this to find out how many times the add function is called, but I cannot think of a way to achieve it. Does anyone have any hints that can point me in the right direction?

I read these two articles ( 1 , 2 ) on the currying function, and I understand them, but I'm not sure how to do currying when dealing with a variable number of arguments.

+5
source share
2 answers

This is not possible, use the value of ().

 function add(initNum) { var sum = initNum; var callback = function (num) { sum += num; return callback; }; callback.valueOf = function () { return sum; }; return callback; }; console.log(add(1)(2)==3); //true console.log(add(1)(1)+1); //3 console.log(add(1)(2)(3).valueOf()); //6 
+2
source

It is not possible to execute a variational function with an unknown number of arguments.

Where add is a variational function, you can do something like

 var add5 = curryN(add, 5); add5(1)(2)(3)(4)(5); //=> 15 var add3 = curryN(add, 3); add3(1)(2)(3); //=> 6 

There simply cannot be avoided, because the curries function will continue to return the function until the last argument is received, after which the calculation will be started.


The only other option is to create a way to "short circuit" the arguments and notify the function that the arguments pass. This will require something like

 var xadd = curryUntilUndefined(add); xadd(1)(2)(3)(4)(5)(undefined); //=> 15 

Here, undefined signals the end of the variational arguments. I really do not recommend this because of other problems that it may create for you. Not to mention that it is not particularly pleasant to watch.

+4
source

Source: https://habr.com/ru/post/1236732/


All Articles