Created
May 2, 2012 08:31
-
-
Save danneu/2575089 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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