Suppose I have the following add function that takes an unlimited number of arguments.
function add () { var total = 0; var args = Array.prototype.slice.call(arguments, 0); for (var i=0; i<args.length; i++) { total += arguments[i]; } return total; }
and the next curry function.
function curryFunction(orig_func) { var ap = Array.prototype; var args = arguments; function fn() { if (arguments.length != 0) { ap.push.apply(fn.args, arguments); return fn; } else { return orig_func.apply(this, fn.args); } }; return function() { fn.args = ap.slice.call( args, 1 ); return fn.apply( this, arguments ); }; }
Then I want to do something like:
var f = curryFunction(add); var a = f(3)(4)(3); var b = f(10)(3); var result1 = a();
However, I always get 13 for both () and b (), I assume in the line
fn.args = ap.slice.call(args, 1);
the existing array [3,4,3] is overwritten with []. Can someone please give me a hint on how to make this work? Thanks
javascript
MrPeru
source share