Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# Cache a func with multiple args like Math.max(1, 2, 3)
Function::cached = ->
cache = {}
(args...) => # Note: could've used a regular `->` and keep the `self = @`
argsKey = args.join()
if argsKey of cache
console.log "Hitting cache with #{argsKey}"
return cache[argsKey]
console.log "Cache miss..."
return cache[argsKey] = @(args...)
Math.max = Math.max.cached()
Math.max 1, 2, 3 # cache miss
Math.max 3, 4, 5 # cache miss
Math.max 1, 2, 3 # cache hit
Math.max 1, 2, 3, 4 # cache miss
Math.max 1, 2, 3, 4 # cache hit
// Compiled by Coffeescript
var __slice = [].slice;
Function.prototype.cached = function() {
var self = this;
var cache = {};
return function() {
var args, argsKey;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
argsKey = args.join();
if (argsKey in cache) {
console.log("Hitting cache with " + argsKey);
return cache[argsKey];
}
console.log("Cache miss...");
return cache[argsKey] = _this.apply(null, args);
};
};
Math.max = Math.max.cached();
Math.max(1, 2, 3); // cache miss
Math.max(3, 4, 5); // cache miss
Math.max(1, 2, 3); // cache hit
Math.max(1, 2, 3, 4); // cache miss
Math.max(1, 2, 3, 4); // cache hit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.