Skip to content

Commit a8caeaa

Browse files
committed
Add memoization.
1 parent a0cf20a commit a8caeaa

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Diff for: dynamic-programming/memoization.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Returns the memoized (cached) function.
2+
3+
/*
4+
1. Create an empty cache by instantiating a new Map object.
5+
2. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not.
6+
3. The function keyword must be used in order to allow the memoized function to have its this context changed if necessary.
7+
4. Allow access to the cache by setting it as a property on the returned function.
8+
*/
9+
10+
const memoize = fn => {
11+
const cache = new Map();
12+
const cached = function (val) {
13+
return cache.has(val)
14+
? cache.get(val)
15+
: cache.set(val, fn.call(this, val)) && cache.get(val);
16+
};
17+
cached.cache = cache;
18+
return cached;
19+
};
20+
// See the `anagrams` snippet.
21+
const anagramsCached = memoize(anagrams);
22+
anagramsCached('javascript'); // takes a long time
23+
anagramsCached('javascript'); // returns virtually instantly since it's cached
24+
console.log(anagramsCached.cache); // The cached anagrams map

0 commit comments

Comments
 (0)