Skip to content

Instantly share code, notes, and snippets.

@jasonmw
Created November 11, 2011 05:44
Show Gist options
  • Save jasonmw/1357301 to your computer and use it in GitHub Desktop.
Save jasonmw/1357301 to your computer and use it in GitHub Desktop.
Homework 2 from Mastering JS Class
Math.sin = (function(){
var original_sin = Math.sin;
var cache = {};
return function(n){
if(cache[n] == null){
cache[n] = original_sin(n);
console.log('adding sin of ' + n.toString() + ' to cache');
} else {
console.log('sin cache hit: ' + n.toString());
}
return cache[n];
}
})();
Function.prototype.cacher = function(){
var original_fn = this;
var cache = {};
return function(n){
if(cache[n] == null){
cache[n] = original_fn(n);
console.log('cacher adding ' + n.toString() + ' to cache');
} else {
console.log('cacher hit: ' + n.toString());
}
return cache[n];
}
}
// tests
var obj = Math.sin(3);
var obj2 = Math.sin(3);
var obj3 = Math.sin(3);
var obj4 = Math.sin(4);
var obj5 = Math.sin(5);
var obj6 = Math.sin(5);
var atan = Math.tan.cacher();
var obj1 = atan(3);
var obj2 = atan(3);
var obj3 = atan(3);
var obj4 = atan(4);
var obj5 = atan(5);
var obj6 = atan(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment