70 lines
No EOL
2 KiB
JavaScript
70 lines
No EOL
2 KiB
JavaScript
'use strict';
|
|
/*@
|
|
Ox.cache <f> Memoize a function
|
|
<script>
|
|
Ox.test.fn = Ox.cache(function(n) { return n * Math.random(); });
|
|
</script>
|
|
> Ox.test.fn(10) == Ox.test.fn(10);
|
|
true
|
|
> Ox.test.fn(10) == Ox.test.fn.clear()(10);
|
|
false
|
|
@*/
|
|
Ox.cache = function(fn, options) {
|
|
options = Ox.extend({
|
|
async: false,
|
|
key: JSON.stringify
|
|
}, options || {})
|
|
var cache = {},
|
|
ret = function() {
|
|
var args = Ox.toArray(arguments),
|
|
callback,
|
|
key = options.key(args);
|
|
function callback() {
|
|
// cache all arguments passed to callback
|
|
cache[key] = Ox.toArray(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, args.slice(0, -1).concat(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) {
|
|
cache = {};
|
|
} else {
|
|
Ox.makeArray(arguments).forEach(function(key) {
|
|
delete cache[key];
|
|
});
|
|
}
|
|
return ret;
|
|
}
|
|
return ret;
|
|
};
|
|
|
|
/*@
|
|
Ox.identity <f> Returns its first argument
|
|
This can be used as a default iterator
|
|
@*/
|
|
Ox.identity = function(val) {
|
|
return val;
|
|
};
|
|
|
|
/*@
|
|
Ox.noop <f> Returns undefined and calls optional callback without arguments
|
|
This can be used to combine a synchronous and an asynchronous code path.
|
|
@*/
|
|
Ox.noop = function(callback) {
|
|
Ox.isFunction(callback) && callback();
|
|
}; |