Skip to content

Instantly share code, notes, and snippets.

@danneu
Created May 2, 2012 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danneu/2575089 to your computer and use it in GitHub Desktop.
Save danneu/2575089 to your computer and use it in GitHub Desktop.
# 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