Function Cache

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function cache(func) {
var _cached = {};
return function() {
var args = [].slice.call(arguments);
var key;
if (!args.length) {
key = 'null';
} else {
key = args.reduce(function(memo, arg) {
if (typeof arg === 'object') {
arg = JSON.stringify(arg);
}
memo += String(arg);
return memo;
},'');
}
if (!(key in _cached)) {
_cached[key] = func.apply(this, args);
}
return _cached[key];
};
}