Request to write a function add (), respectively, to achieve the following effect:
(1) Console.log (Add (1) (2) (3) (4) ()); // Ten (2) Console.log (add) (3,4) ()); // Ten (3) Console.log (Add (3,4)); // Ten
for (1) and (2), there are two ways to achieve: the idea of pure closure and the function of curry thinking.
First, closure of the idea
(1) Solution (Closure implementation)
function add (ARG) { // body ... Let sum = 0; Sum +=ARG; return function (tmarg) { // body ... if (Arguments.length = = 0 return sum; else {sum +=TMARG; return Arguments.callee; } }}
(2) Solution
functionAdd (ARG) {//body ...Let sum = 0; Sum= Array.prototype.slice.call (arguments). reduce ((b) = =returnA +b;},sum); return function(tmarg) {//body ... if(Arguments.length = = 0) { returnsum; }Else{sum= Array.prototype.slice.call (arguments). reduce ((b) = =returnA +b;},sum); returnArguments.callee; } }}
Second, the thinking of the function curry
Popular understanding, because the function of the curry has such a feature: it can "accumulate" the parameters of the function (whether it is foo () or foo (1) (2) (3) The chain form), and deferred execution. You can accumulate multiple parameters into an array and perform the summation in the last step.
The common form of curry:
function Curry (FN) { // body ... var args = Array.prototype.slice.call (arguments,1 return function () { // body ... var innerargs = Array.prototype.slice.call ( arguments); var finalargs = Args.concat (Innerargs); Console.log (Finalargs); return fn.apply (null ,finalargs); };}
(2) Solution:
function Add () { = 0; var _args = Array.prototype.slice.call (arguments); var function () { if(arguments.length = = = 0) { = _args.reduce (A, b) = = {return A + b;},sum); } _args.push.apply (_args,[].slice.call (arguments)); return Tmpf; }
For question (3):
functionAdd (ARG) {//body ...Let sum = 0; Sum= Array.prototype.slice.call (arguments). reduce ((b) = =returnA +b;},sum); varTmpf =function(tmarg) {//body ... if(Arguments.length = = 0) { returnsum; }Else{sum= Array.prototype.slice.call (arguments). reduce ((b) = =returnA +b;},sum); returnTmpf; } }; Tmpf.tostring= Tmpf.valueof =function () { //body ... returnsum; } returnTmpf;}
A JavaScript face question (Closure and function currying)