Skip to content

Instantly share code, notes, and snippets.

@stdclass
Created December 12, 2011 20:59
Show Gist options
  • Save stdclass/1469065 to your computer and use it in GitHub Desktop.
Save stdclass/1469065 to your computer and use it in GitHub Desktop.
JS Master Class Homework
// 1. Write a class to support the following code:
var thomas = new Person('Thomas');
var amy = new Person('Amy');
thomas.name // --> "Thomas"
// 2. Add a getName() method to all Person objects, that outputs
// the persons name.
thomas.getName() // --> "Thomas"
// 3. Write a statement that calls Thomas's getName function,
// but returns "Amy". (Don't change or redefine the getName
// function in any way.)
// 4. Remove the getName() method from all Person objects.
function Person( name ){
this.name = name;
};
Person.prototype = {
getName: function(){
return this.name;
}
};
thomas.getName.call(amy);
delete Person.prototype.getName;
// 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)
//
// 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.prototype.cached = function(){
var origFunc = this
, cache = {};
return function( arg ){
if( cache[ arg ] === undefined )
cache[ arg ] = origFunc( arg );
return cache[ arg ];
};
};
var isPrime = function( num ) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}.cached();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment