Last active
August 29, 2015 14:02
-
-
Save Williammer/a1e6620cf8626394c39c to your computer and use it in GitHub Desktop.
jsPattern.prototypeCacheVal.js - cache value with a new Function.prototype method.
This file contains hidden or 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
| 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(); | |
| assert(isPrime(17), "17 is prime"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment