javascript - Recursion with dynamic arguments -


this question has answer here:

this interview question haven't yet been able figure out. consider following:

function recurse(a) {     return function(b) {         console.log(a + b);     } }  //this log '5' in console recurse(2)(3); 

now asked write function take n number of arguments , work same way logging final summation of argument values. meaning:

//this should log '13' recurse(2)(3)(1)(7) 

how can such function written? have tried thinking on in terms of recursion, dynamic arguments etc. haven't been able write down concrete.

here's simplest version think of:

function add (a) {    return function (b) {      return b == null ? : add(a+b);    }  }    console.log(     add(2)(3)()   );  console.log(    add(10)(100)(1000)(4)()   );

in es6, it's compact!

let add = => b => b == null ? : add(a+b); 

note

the trouble question function can either return function or number. following code:

let result = add(2)(3); 

is equivalent to:

/*1*/ let partialresult = add(2); /*2*/ let result = partialresult(3); 

in line 1, add doesn't know whether being called last argument or not! in other words, doesn't know whether partialresult should number, or function called argument.

nina scholz gives solution partialresult behave number when treated primitive, , function when called function. in solution, partialresult acts function, , returns sum when called without argument.

the first approach requires language-specific mechanism "behaving number" under conditions. if interview javascript, it's best approximation! in language-agnostic context, asking impossible.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -