make Ox.cache work for aynchronous functions

This commit is contained in:
rolux 2012-04-03 15:09:05 +02:00
parent 0bf4d5a0f5
commit 4613c96a01

View file

@ -9,12 +9,36 @@ Ox.cache <f> Memoize a function
> Ox.test.fn(10) == Ox.test.fn.clear()(10); > Ox.test.fn(10) == Ox.test.fn.clear()(10);
false false
@*/ @*/
Ox.cache = function(fn) { Ox.cache = function(fn, options) {
options = Ox.extend({
async: false,
key: JSON.stringify
}, options || {})
var cache = {}, var cache = {},
ret = function() { ret = function() {
var key = JSON.stringify(Ox.makeArray(arguments)); var args = Ox.makeArray(arguments),
return key in cache ? cache[key] callback,
: (cache[key] = fn.apply(this, arguments)); 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];
}
}; };
ret.clear = function() { ret.clear = function() {
if (arguments.length == 0) { if (arguments.length == 0) {