Skip to content

Instantly share code, notes, and snippets.

@christophevg
Created January 21, 2011 13:43

Revisions

  1. christophevg created this gist Jan 21, 2011.
    43 changes: 43 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // 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.

    Function.prototype.withCaching = function withCaching() {
    if( ! this.cache ) { this.cache = {}; } // lazy initialization of cache
    var method = this;
    return function(input) {
    if( typeof method.cache[input] == "undefined" ) {
    var result = method.apply(this, [ input ]);
    method.cache[input] = result;
    }
    return method.cache[input];
    };
    };

    // Part 2.
    // Use this new function to refactor the code example.
    // Some good test numbers: 524287, 9369319, 2147483647 (all primes)

    var isPrime = function( num ) {
    console.log( "looking ..." );
    var prime = num != 1;
    // everything but 1 can be prime
    for ( var i = 2; i < num; i++ ) {
    if ( num % i == 0 ) {
    prime = false;
    break;
    }
    }
    return prime;
    }.withCaching();

    console.log( isPrime( 4 ) ); // looking ... false
    console.log( isPrime( 4 ) ); // false

    console.log( isPrime( 524287 ) ); // looking ... true
    console.log( isPrime( 524287 ) ); // true