oxjs/source/Ox/js/Function.js

55 lines
1.6 KiB
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, options) {
options = Ox.extend({
async: false,
key: JSON.stringify
}, options || {})
2012-01-07 07:20:02 +00:00
var cache = {},
ret = function() {
var args = Ox.makeArray(arguments),
callback,
key = options.key(args);
function callback() {
// cache all arguments passed to callback
cache[key] = Ox.makeArray(arguments);
// call the original callback
Ox.last(args).apply(this, arguments);
}
if (options.async) {
if (!(key in cache)) {
// call function with patched callback
fn.apply(this, Ox.merge(Ox.sub(args, 0, -1), callback));
} else {
// call callback with cached arguments
callback.apply(this, cache[key])
}
} else {
if (!(key in cache)) {
cache[key] = fn.apply(this, args);
}
return cache[key];
}
2012-01-07 07:20:02 +00:00
};
ret.clear = function() {
if (arguments.length == 0) {
cache = {};
} else {
Ox.toArray(arguments).forEach(function(key) {
delete cache[key];
});
}
return ret;
}
return ret;
};