For example
Copy codeThe Code is as follows: var flower = function (){
Var t = 0, I = 0;
For (; I <5000000; I ++ ){
T ++;
}
Return t;
}
Flower returns t value
Suppose this function takes 2-3 seconds.
Through the Memoization function, when the same value is searched again, the cached value is obtained directly and immediately returned;
Memoization Function
Copy codeCode: var Memoize = function (fn, cache, refetch, obj ){
Cache = cache | {}; // used to cache results
Return function (){
Var k = arguments [1]? Array. prototype. join. call (arguments, '_'): arguments [0]; // multiple parameters are separated '_'.
If (! (K in cache) | (refetch & cache [k] = refetch) {// if it is not in the cache list and is equal to the given refetch value, perform the operation again
Cache [k] = fn. apply (obj | fn, arguments); // The obj parameter can be used to change the this pointer.
}
Return cache [k]; // return results
}
}
Demo: