Created
March 8, 2013 16:24
-
-
Save bradpauly/5117670 to your computer and use it in GitHub Desktop.
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.cache = function(){ | |
var _cache = {}; | |
var key = function(args) { | |
var sig = 'x', index = args.length; | |
while (index--) { | |
sig += args[index].toString(); | |
} | |
return sig; | |
} | |
this.store = function(args, v){ | |
_cache[key(args)] = v; | |
return v; | |
} | |
this.fetch = function(args) { | |
var k = key(args); | |
if (k in _cache) { | |
return _cache[k]; | |
} else { | |
return null; | |
} | |
} | |
return this; | |
}(); | |
function sum() { | |
if (sum.cache.fetch(arguments) != null) { | |
return sum.cache.fetch(arguments); | |
} | |
var total = 0, length = arguments.length; | |
while (length--) { | |
total += arguments[length]; | |
} | |
return sum.cache.store(arguments, total) | |
} | |
function sin(num) { | |
if (sin.cache.fetch(arguments) != null) { | |
return sin.cache.fetch(arguments); | |
} | |
var s = Math.sin(num) | |
return sin.cache.store(arguments, s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment