make Ox.cache work for aynchronous functions
This commit is contained in:
parent
0bf4d5a0f5
commit
4613c96a01
1 changed files with 28 additions and 4 deletions
|
@ -9,12 +9,36 @@ Ox.cache <f> Memoize a function
|
|||
> Ox.test.fn(10) == Ox.test.fn.clear()(10);
|
||||
false
|
||||
@*/
|
||||
Ox.cache = function(fn) {
|
||||
Ox.cache = function(fn, options) {
|
||||
options = Ox.extend({
|
||||
async: false,
|
||||
key: JSON.stringify
|
||||
}, options || {})
|
||||
var cache = {},
|
||||
ret = function() {
|
||||
var key = JSON.stringify(Ox.makeArray(arguments));
|
||||
return key in cache ? cache[key]
|
||||
: (cache[key] = fn.apply(this, arguments));
|
||||
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];
|
||||
}
|
||||
};
|
||||
ret.clear = function() {
|
||||
if (arguments.length == 0) {
|
||||
|
|
Loading…
Reference in a new issue