Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created December 27, 2013 16:52
Show Gist options
  • Select an option

  • Save kevinmeredith/8149561 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/8149561 to your computer and use it in GitHub Desktop.
Power of closures (from Secrets of the JavaScript Ninja)
Function.prototype.memoized = function(key) {
this._values = this._values || {};
return this._values[key] !== undefined ?
this._values[key] :
this._values[key] = this.apply(this, arguments);
}
Function.prototype.memoize = function() {
var fn = this;
return function() {
return fn.memoized.apply(fn, arguments);
}
}
var isPrime = (function(num) {
var prime = num != 1;
for (var i = 2; i < num; i++) {
if(num % i == 0) {
prime = false;
break;
}
}
return prime;
}).memoize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment