Skip to content

Instantly share code, notes, and snippets.

@jamesmenera
Created March 7, 2013 20:52
Show Gist options
  • Save jamesmenera/5111690 to your computer and use it in GitHub Desktop.
Save jamesmenera/5111690 to your computer and use it in GitHub Desktop.
Homework 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)
//
// Hints: this is in a lot of ways similiar to the way currying works
// it combines using built-in prototypes with functional programming
// then use this new function to refactor the isPrime function that is given
// the current isPrime function has caching built-in—but we want to have a generic solution that you can re-use for other functions that have the same signature (same arguments)
// note that this caching function only has to work with functions that have an arity of 1 and take a number or string as argument (arity of 1 means functions that take exactly one argument)
// bonus points (extra-hard!) for a solution that supports one or more arguments
//
// In other words, if you have this code:
//
// Function.prototype.cached = function(){
// ? (what goes here?)
// }
//
// // For the isPrime function
//
// var cachedIsPrime = isPrime.cached();
// isPrime(11); // --> true (cache miss, calls original isPrime(1) function, stores return value in cache)
// isPrime(11); // --> true (cache hit, directly returns value)
//
// // ..but it short work on anything that takes just one (numeric) argument:
//
// var cachedSin = Math.sin.cached();
//
// cachedSin(1); // --> 0.8414709848078965 (cache miss, calls original Math.sin(1) function, stores return value in cache)
// cachedSin(1); // --> 0.8414709848078965 (cache hit, directly returns value)
function isPrime( num ) {
if ( isPrime.cache[ num ] != null )
return isPrime.cache[ num ];
// everything but 1 can be prime
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
isPrime.cache[ num ] = prime;
return prime;
}
isPrime.cache = {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment