Skip to content

Instantly share code, notes, and snippets.

@wallin
Created September 16, 2011 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallin/1222235 to your computer and use it in GitHub Desktop.
Save wallin/1222235 to your computer and use it in GitHub Desktop.
/////// Homework 1 ///////
var logCar = function (car) {
car = car || {};
car.make = car.make || 'anonymous car';
car.color = car.color || 'uncolored';
var a = /^[aeiouy]/.test(this.color) ? 'an' : 'a';
console.log('I\'m ' + a + ' ' + car.color + ' ' + car.make);
};
var BMW = { color: 'blue', make: 'BMW' };
// --------
var Car = function (make, color) {
if (make != null) {
this.make = make;
}
if (color != null) {
this.color = color;
}
};
Car.prototype = {
make: 'anonymous car',
color: 'uncolored',
log: function () {
var a = /^[aeiouy]/.test(this.color) ? 'an' : 'a';
console.log('I\'m ' + a + ' ' + this.color + ' ' + this.make);
}
};
/////// Homework 2 ///////
Function.prototype.cached = function () {
return (function (func) {
var cache = {};
return function (num) {
if (!(num in cache)) {
cache[num] = func(num);
}
return cache[num];
};
}(this));
};
var isPrime = (function ( 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;
}).cached();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment