javascript - Function calling 2 ways with multiple arguments -
as of know can create simple function this.
function calc(a,b){ return a+b } calc(1,1); //returns 2
we can make this
function calc(a){ return function(b){ return a+b } } calc(1)(1); //returns 2
what if had multiple arguments?
function calc() { function r(arg) { var = []; for(var = 0, l = arg.length; < l; i++){ a[i] = arg[i]; } return a.reduce(function(p, c) { return p + c; }); } var res = r(arguments); return function() { res += r(arguments); return res; } }
this works calc(1,2)(1)
doesn't calc(1,2,1)
is there way combine both versions? means when calling calc(1,1)
call calc(1)(1)
, both still return 2.
or calc(1,2,3)
calc(1,2)(3)
calc(1)(2,3)
return 6
it needs know how many arguments calculation after ;-)
you can make function turns things sort of function :
function curry(f){ var args = []; return addargs; function addargs(){ args=args.concat([].slice.call(arguments)); return args.length<f.length? addargs.bind(this) : f.apply(this,args); } }
then can :
var calc = curry(function(a,b,c){return a+b+c}); calc(1,2)(3); // = 6
but can't have take variable number of arguments and curry - wouldn't know when return answer
Comments
Post a Comment