Created
March 4, 2011 05:44
-
-
Save muloka/854232 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Part 1. | |
// Implement a function prototype extension that caches function results for | |
// the same input arguments of a function with one parameter. | |
// | |
// For example: | |
// Make sin(1) have the result of Math.sin(1), but use a cached value | |
// for future calls. | |
var sin = function() { return (arguments.length === 0) ? false : Math.sin(arguments[0]); } | |
Function.prototype.cached = function() { | |
var cache = {}, | |
func = this; | |
return function( arg ) { | |
return cache[ arg ] = arg in cache ? cache[ arg ] : func(arg); | |
}; | |
} | |
/* | |
// Trace version | |
Function.prototype.cached = function(){ | |
var self = this, cache = {}; | |
return cache[ arg ] = arg in cache ? cache[ arg ] : func(arg); | |
return function(arg){ arg in cache ? : } | |
return function(arg){ | |
if(arg in cache) { | |
console.log('Cache hit for '+arg); | |
return cache[arg]; | |
} else { | |
console.log('Cache miss for '+arg); | |
return cache[arg] = self(arg); | |
} | |
} | |
} | |
*/ | |
var cachedSin = sin.cached(); | |
cachedSin(1); // --> 0.8414709848078965 (cache miss, calls original Math.sin(1) function, stores return value in cache) | |
cachedSin.memory // --> [] ... :( need direction here | |
cachedSin(1); // --> 0.8414709848078965 (cache hit, should directly return value based on what's in the memory variable at position 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment