Ox.cache: extend options only once

This commit is contained in:
rolux 2013-12-01 13:12:07 +01:00
parent fe40220d0b
commit adea34c84e

View file

@ -16,36 +16,36 @@ Ox.cache <f> Memoize a function
@*/ @*/
// TODO: add async test // TODO: add async test
Ox.cache = function(fn, options) { Ox.cache = function(fn, options) {
var cache = {}, var cache = {}, ret;
ret = function() { options = Ox.extend({
options = Ox.extend({ async: false,
async: false, key: JSON.stringify
key: JSON.stringify }, options || {});
}, options || {}); ret = function() {
var args = Ox.toArray(arguments), key = options.key(args); var args = Ox.slice(arguments), key = options.key(args);
function callback() { function callback() {
// cache all arguments passed to callback // cache all arguments passed to callback
cache[key] = Ox.toArray(arguments); cache[key] = Ox.slice(arguments);
// call the original callback // call the original callback
Ox.last(args).apply(this, arguments); Ox.last(args).apply(this, arguments);
} }
if (options.async) { if (options.async) {
if (!(key in cache)) { if (!(key in cache)) {
// call function with patched callback // call function with patched callback
fn.apply(this, args.slice(0, -1).concat(callback)); fn.apply(this, args.slice(0, -1).concat(callback));
} else {
// call callback with cached arguments
setTimeout(function() {
callback.apply(this, cache[key]);
});
}
} else { } else {
if (!(key in cache)) { // call callback with cached arguments
cache[key] = fn.apply(this, args); setTimeout(function() {
} callback.apply(this, cache[key]);
return 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) {
cache = {}; cache = {};
@ -99,7 +99,7 @@ Ox.queue = function(fn, maxThreads) {
processing = [], processing = [],
queued = [], queued = [],
ret = Ox.cache(function() { ret = Ox.cache(function() {
var args = Ox.toArray(arguments); var args = Ox.slice(arguments);
queued.push({args: args, key: getKey(args)}); queued.push({args: args, key: getKey(args)});
process(); process();
}, {async: true, key: getKey}), }, {async: true, key: getKey}),