Last active
December 16, 2015 11:39
-
-
Save Jabher/5429311 to your computer and use it in GitHub Desktop.
Caching factory; usage syntax: cache = new CacheFactory(Math.random)
cache(1)> 0.808444140246138;
cache(2)> 0.9461546286474913;
cache(1)> 0.808444140246138;
This file contains 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
CacheFactory = (function () { | |
function compareThings() { | |
var names = [ | |
arguments[0]["name"].toLowerCase(), | |
arguments[1]["name"].toLowerCase() | |
]; | |
if (names[0] < names[1]) { | |
return -1; | |
} | |
if (names[0] > names[1]) { | |
return 1; | |
} | |
return 0; | |
} | |
return function (func) { | |
var cache = {}; | |
return function (request) { | |
var stringified_request; | |
if (request) { | |
switch (typeof request) { | |
case typeof []: | |
var sorted_request = request.sort(compareThings); | |
stringified_request = JSON.stringify(sorted_request); | |
break; | |
case typeof '': | |
stringified_request = request; | |
break; | |
case typeof 0: | |
stringified_request = request.toFixed(2); | |
break; | |
case typeof true: | |
case typeof function () {}: | |
stringified_request = request.toString(); | |
break; | |
} | |
} else { | |
switch (request) { | |
case 0 / 0: | |
stringified_request = 'NaN'; | |
break; | |
case null: | |
stringified_request = 'null'; | |
break; | |
case 1 / 0: | |
stringified_request = 'Infinity'; | |
break; | |
case -1 / 0: | |
stringified_request = '-Infinity'; | |
break; | |
} | |
} | |
stringified_request = stringified_request || 'undefined'; | |
if (cache[stringified_request] === void 0) { | |
cache[stringified_request] = func(request); | |
} | |
return cache[stringified_request] | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment