JavaScript cache proxy mode

1. Principle: The cache proxy can provide temporary storage for some expensive calculation results. In the next calculation, if the passed parameters are consistent with the previous ones, it can directly return the previously stored calculation results to improve efficiency and save costs.

2. Examples:

var mult = function(){
    console.log('开始计算乘机');
    var a = 1;
    for(var i = 0, l = arguments.length;i < l;i++){
        a = a*arguments[i];
    }
    return a;
};

var proxyMult = (function(){
   var cache = {};
   return function(){
       var args = Array.prototype.join.call( arguments, ',');
       if(args in cache){
           return cache[args]; //直接返回
       }
        return cache[args] = mult.apply( this, arguments);
   }
})();

proxyMult( 1,2,3,4);  //输出:24
proxyMult( 1,2,3,4);  //输出:24
3. Analysis: Through the cache proxy mode, the decision can be handed over to the proxy function object proxyMult, and the mult function can focus on its own responsibilities.

Guess you like

Origin blog.csdn.net/joyksk/article/details/79800517