Skip to content

Instantly share code, notes, and snippets.

@natebunnyfield
Created July 30, 2010 05:28
Show Gist options
  • Save natebunnyfield/499955 to your computer and use it in GitHub Desktop.
Save natebunnyfield/499955 to your computer and use it in GitHub Desktop.
homework from javascriptmasterclass.com; paired with http://github.com/chrisdickinson
var Cache = function() {
this.table = {};
};
Cache.prototype = {
'get': function(key) {
return this.table[key];
},
'set': function(key, value) {
return this.table[key] = value;
}
};
var cache = function(argument) {
var cacheResult;
if (!this._cacheObject) {
this._cacheObject = new Cache();
}
cacheResult = this._cacheObject.get(argument);
if (cacheResult === undefined) {
cacheResult = this._cacheObject.set(argument, this(argument));
}
return cacheResult;
};
exports.Cache = Cache;
Function.prototype.cache = cache;
var cache = require('./cache');
var isPrime = function(num) {
num = Math.abs(num);
if (num.toString().indexOf('.') !== -1) {
return false;
}
if (num < 2) {
return false;
}
for (var i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
};
exports.isPrime = function(num) {
return isPrime.cache(num);
};
var cache = require('../cache'),
prime = require('../prime'),
vows = require('vows'),
assert = require('assert');
var suite = vows.describe('cache');
suite.addBatch({
'Call isPrime': {
'with a prime number': function() {
assert.isTrue(prime.isPrime(17));
assert.isTrue(prime.isPrime('19'));
assert.isTrue(prime.isPrime(524287));
},
'with a non-prime number': function() {
assert.isFalse(prime.isPrime(54.212));
assert.isFalse(prime.isPrime(0));
assert.isFalse(prime.isPrime(-10));
assert.isFalse(prime.isPrime(1));
assert.isFalse(prime.isPrime("1"));
assert.isFalse(prime.isPrime(20));
}
}
}).addBatch({
'Call cache': {
'with an empty cache': function() {
var fn = Math.sin,
rando = Math.random();
assert.isUndefined(fn._cacheObject);
var result = fn.cache(rando),
realResult = fn(rando);
assert.instanceOf(fn._cacheObject, cache.Cache);
assert.equal(result, realResult);
},
'with a populated cache': function() {
var fn = Math.sin,
rando = Math.random(),
secretRando = Math.random();
fn.cache(rando);
fn._cacheObject.set(rando, secretRando);
assert.equal(fn.cache(rando), secretRando);
assert.notEqual(fn.cache(rando), fn(rando));
},
'with non-truthy value in cache': function() {
var fn = Math.sin,
rando = Math.random();
assert.equal(fn.cache(rando), fn(rando));
fn._cacheObject.set(rando, false);
assert.equal(fn.cache(rando), false);
}
}
}).run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment