public
Created

  • Download Gist
cached-multi-args.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.