From 4613c96a013a040eae7304fbde0d74d502520dfc Mon Sep 17 00:00:00 2001 From: rolux Date: Tue, 3 Apr 2012 15:09:05 +0200 Subject: [PATCH] make Ox.cache work for aynchronous functions --- source/Ox/js/Function.js | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/source/Ox/js/Function.js b/source/Ox/js/Function.js index ae081adc..02d79167 100644 --- a/source/Ox/js/Function.js +++ b/source/Ox/js/Function.js @@ -9,12 +9,36 @@ Ox.cache 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) {