oxjs/source/Ox/js/Function.js

31 lines
785 B
JavaScript
Raw Normal View History

'use strict';
2012-01-07 07:20:02 +00:00
/*@
Ox.cache <f> Memoize a function
<script>
Ox.test.fn = Ox.cache(function(n) { return n * Math.random(); });
2012-01-07 07:20:02 +00:00
</script>
> Ox.test.fn(10) == Ox.test.fn(10);
2012-01-07 07:20:02 +00:00
true
> Ox.test.fn(10) == Ox.test.fn.clear()(10);
2012-01-07 07:20:02 +00:00
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;
};