29 lines
729 B
JavaScript
29 lines
729 B
JavaScript
|
/*@
|
||
|
Ox.cache <f> Memoize a function
|
||
|
<script>
|
||
|
var f = Ox.cache(function(n) { return n * Math.random(); });
|
||
|
</script>
|
||
|
> f(10) == f(10);
|
||
|
true
|
||
|
> f(10) == f.clear()(10);
|
||
|
false
|
||
|
@*/
|
||
|
Ox.cache = function(fn) {
|
||
|
var cache = {},
|
||
|
ret = function() {
|
||
|
var key = JSON.stringify(Ox.makeArray(arguments));
|
||
|
return key in cache ? cache[key]
|
||
|
: (cache[key] = fn.apply(this, arguments));
|
||
|
};
|
||
|
ret.clear = function() {
|
||
|
if (arguments.length == 0) {
|
||
|
cache = {};
|
||
|
} else {
|
||
|
Ox.toArray(arguments).forEach(function(key) {
|
||
|
delete cache[key];
|
||
|
});
|
||
|
}
|
||
|
return ret;
|
||
|
}
|
||
|
return ret;
|
||
|
};
|