Some time ago, I saw an interview question about currying sent by someone in the group, and it was very interesting to see it.

I haven't written an essay online for a long time. I watched a teaching video of C recently. I was inspired by the teacher. I remembered the blog garden, and it was forgotten for a while. . .

I remember that I saw an interview question in the group before, asking to write a function that returns the sum of any parameters after calling it. The result of the request is this:

sum(1,2) // returns 3

sum(1)(2) // returns 3

sum(1)(2,3) // returns 6

sum(1)(2)(3) //return 6

It was very interesting to read at the time, and I didn’t know what currying was. I don’t know why I suddenly remembered this topic. Recently, I just saw someone talking about the topic of currying, so I tried to do it in the debug mode of chrome:

 1 function sum(){
 2     let _arg = [];
 3     _arg.push(...arguments);
 4     var ret = function(){
 5         _arg.push(...arguments);
 6         // arguments.callee.valueOf=()=>(_arg.reduce((a,b)=>a+b,0));
 7         return arguments.callee;
 8     }
 9     ret.valueOf=()=>(_arg.reduce((a,b)=>a+b,0));
10     return ret;
11 }

The point here is valueOf, js native objects basically have toString and valueOf methods, except for null and undefined, if valueOf returns the native object itself, overwrite the valueOf of the returned function to return the desired result (summation of parameters) .

In addition, there is a closure. The function returned by _arg declared in sum needs to be stored in a collection each time it is called for the final summation. Simply meet the requirements of the subject.

 

Hope to keep the record, the process of accumulating little by little.

Explanation of terms (excerpted from Baidu Encyclopedia):

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324815505&siteId=291194637