Created
November 11, 2011 17:04
-
-
Save phaze9/1358560 to your computer and use it in GitHub Desktop.
JavaScript Masterclass Homework
This file contains 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
// Exercise 1 - OO || !OO | |
// Define a data structure for cars (make and color), and a function | |
// that logs a string like "I'm a red Mercedes" to the console. | |
// Make two versions: a functional version, and a object-oriented version. | |
var logCar = function(car) { | |
console.log("I'm a " + car.color + ' ' + car.make); | |
} | |
logCar({ color: 'blue', make: 'BMW' }); | |
var Car = function(make, color) { | |
this.log = function() { | |
console.log("I'm a " + color + ' ' + make); | |
} | |
} | |
new Car('Ferrari', 'red').log(); |
This file contains 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. | |
// | |
// Part 2. | |
// Use this new function to refactor the code example. | |
// Some good test numbers: 524287, 9369319, 2147483647 (all primes) | |
Function.prototype.cached = function() { | |
var cache = { } | |
var method = this; | |
return function(input) { | |
var cached = cache[input]; | |
if ( cached == null ) { | |
cached = method(input); | |
cache[input] = cached; | |
} | |
return cached; | |
} | |
} | |
Math.sin = Math.sin.cached(); | |
console.log(Math.sin(1)); | |
console.log(Math.sin(1)); | |
function isPrime(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; | |
} | |
} | |
return prime; | |
} | |
isPrime = isPrime.cached(); | |
console.log(isPrime(2147483647)); | |
console.log(isPrime(2147483647)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment