javascript - Recursion with dynamic arguments -
this question has answer here:
- variadic curried sum function 7 answers
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
Post a Comment