-
Notifications
You must be signed in to change notification settings - Fork 413
/
memoize.js
39 lines (35 loc) · 1.36 KB
/
memoize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Return a memoized version of f.
// It only works if arguments to f all have distinct string representations.
function memoize(f) {
const cache = new Map(); // Value cache stored in the closure.
return function(...args) {
// Create a string version of the arguments to use as a cache key.
let key = args.length + args.join("+");
if (cache.has(key)) {
return cache.get(key);
} else {
let result = f.apply(this, args);
cache.set(key, result);
return result;
}
};
}
// Return the Greatest Common Divisor of two integers using the Euclidian
// algorithm: http://en.wikipedia.org/wiki/Euclidean_algorithm
function gcd(a,b) { // Type checking for a and b has been omitted
if (a < b) { // Ensure that a >= b when we start
[a, b] = [b, a]; // Destructuring assignment to swap variables
}
while(b !== 0) { // This is Euclid's algorithm for GCD
[a, b] = [b, a%b];
}
return a;
}
const gcdmemo = memoize(gcd);
gcdmemo(85, 187) // => 17
// Note that when we write a recursive function that we will be memoizing,
// we typically want to recurse to the memoized version, not the original.
const factorial = memoize(function(n) {
return (n <= 1) ? 1 : n * factorial(n-1);
});
factorial(5) // => 120: also caches values for 4, 3, 2 and 1.