member-berry
Memoize a function of n args with O(n) recall and no memory leaks.
This function is similar to lodash.memoize, the main difference
is that it memoizes any number of arguments, makes sure not to
leak any memory while maintaining a complexity of
O(arguments.length
).
Usage
;var { var hash = 0 i chr len; if strlength === 0 return hash; for i = 0 len = strlength; i < len; i++ chr = str; hash = hash << 5 - hash + chr; hash |= 0; // Convert to 32bit integer return hash;}; { console; var hash = 0 for var i = 0; i < argumentslength; i++ hash = return hash;}var memoized = ; // calculates // doesn't recalculate var obj = {}; // calculates // doesn't recalculate // calculates // doesn't recalculate
Implementation
The technique used to achive O(n) lookup, is to use a trie-like data structure to store the cached values. Here's a basic snippet with accompanying explaination:
var { return a + b + c; };var memoized = ; /* memoized internal cache looks something like this:{ 1: { 2: { 3: { result: "123" } } }}*/
member-berry
uses weakmaps to avoid holding onto object
references longer than needed. Weakmaps can't use primitive
values as keys so there's also a "wrapped" object associated
with primitives.