Created
March 21, 2017 01:33
-
-
Save yy-dev7/fab5e037f3392d3c12404336bbaa24fe to your computer and use it in GitHub Desktop.
cacheProxyFactory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cacheProxyFactory(fn) { | |
var cache = {} | |
return function() { | |
var args = [].join.call(arguments, ',') | |
if (args in cache) { | |
return cache[args] | |
} | |
return cache[args] = fn.apply(this, arguments) | |
} | |
} | |
function mult() { | |
console.log('开始计算乘积') | |
var a = 1 | |
for (var i = 0, l = arguments.length; i < l; i++) { | |
a = a * arguments[i] | |
} | |
return a | |
} | |
// 缓存每次计算的乘积 | |
var proxyMult = cacheProxyFactory(mult) | |
console.log(proxyMult(1, 2)); | |
console.log(proxyMult(1, 2, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment