oxjs/source/Ox/js/Function.js

31 lines
744 B
JavaScript
Raw Normal View History

'use strict';
2012-01-07 07:20:02 +00:00
/*@
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;
};