最早期的curry函數有點多態的意味,就是根據函數參數在內部選用分支: 復制代碼 代碼如下: //http://www.openlaszlo.org/pipermail/laszlo-user/2005-March/000350.html // ★★On 8 Mar 2005, at 00:06, Steve Albin wrote: function add(a, b) { if (arguments.length < 1) { return add; } else if (arguments.length < 2) { return function(c) { return a + c } } else { return a + b; } }
var myadd = add( 2 ); var total = myadd(3);
日本的一個先行者可能在未搞清arguments也能用Array的原生方法轉換為數組的時候,用非常復雜的正則與eval搞出一個更接近現代currying意味的函數。 復制代碼 代碼如下: function curry(fun) { if (typeof fun != 'function') { throw new Error("The argument must be a function."); } if (fun.arity == 0) { throw new Error("The function must have more than one argument."); }
var funText = fun.toString(); var args = /function .*\((.*)\)(.*)/.exec(funText)[1].split(', '); var firstArg = args.shift(); var restArgs = args.join(', '); var body = funText.replace(/function .*\(.*\) /, "");
var curriedText = "function (" + firstArg + ") {" + "return function (" + restArgs + ")" + body + "}";