Skip to content

Instantly share code, notes, and snippets.

@sdepold
Created October 19, 2010 20:11
Show Gist options
  • Save sdepold/635003 to your computer and use it in GitHub Desktop.
Save sdepold/635003 to your computer and use it in GitHub Desktop.
var cachy = (function() {
var cache = {}
var executor = function(func, args) {
var funcIdentifier = func.toString(),
argsIdentifier = args.join(", ")
if(cache.hasOwnProperty(funcIdentifier) && cache[func.toString()].hasOwnProperty(argsIdentifier)) {
console.log("cached baby!")
return cache[funcIdentifier][argsIdentifier]
} else {
console.log("not cached yet!")
cache[funcIdentifier] = cache[funcIdentifier] || {}
return cache[funcIdentifier][argsIdentifier] = func.call(null, args)
}
}
return executor
})()
var sin = function(arg) {
return Math.sin(arg)
}
console.log(cachy(sin, [2]))
console.log(cachy(sin, [2]))
// 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.
//
// Part 2.
// Use this new function to refactor the code example.
// Some good test numbers: 524287, 9369319, 2147483647 (all primes)
var isPrime = function ( num ) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
console.log(cachy(isPrime, [2]))
console.log(cachy(isPrime, [2]))
console.log(cachy(isPrime, [4]))
console.log(cachy(isPrime, [1]))
console.log(cachy(isPrime, [4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment