-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2630-MemoizeII.js
More file actions
74 lines (68 loc) · 2.62 KB
/
2630-MemoizeII.js
File metadata and controls
74 lines (68 loc) · 2.62 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 2630. Memoize II
// Given a function fn, return a memoized version of that function.
// A memoized function is a function that will never be called twice with the same inputs.
// Instead it will return a cached value.
// fn can be any function and there are no constraints on what type of values it accepts.
// Inputs are considered identical if they are === to each other.
// Example 1:
// Input:
// getInputs = () => [[2,2],[2,2],[1,2]]
// fn = function (a, b) { return a + b; }
// Output: [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}]
// Explanation:
// const inputs = getInputs();
// const memoized = memoize(fn);
// for (const arr of inputs) {
// memoized(...arr);
// }
// For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn().
// For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required.
// For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2.
// Example 2:
// Input:
// getInputs = () => [[{},{}],[{},{}],[{},{}]]
// fn = function (a, b) { return ({...a, ...b}); }
// Output: [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}]
// Explanation:
// Merging two empty objects will always result in an empty object.
// It may seem like there should only be 1 call to fn() because of cache-hits,
// however none of those objects are === to each other.
// Example 3:
// Input:
// getInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; }
// fn = function (a, b) { return ({...a, ...b}); }
// Output: [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}]
// Explanation:
// Merging two empty objects will always result in an empty object.
// The 2nd and 3rd third function calls result in a cache-hit.
// This is because every object passed in is identical.
// Constraints:
// 1 <= inputs.length <= 10^5
// 0 <= inputs.flat().length <= 10^5
// inputs[i][j] != NaN
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const map = new Map(), hash = new Map();
let id = 0;
return function(...args) {
const key = args.map(arg => {
if (!hash.has(arg)) hash.set(arg, id++);
return hash.get(arg);
}).join("-");
if (!map.has(key)) map.set(key, fn.apply(null, args));
return map.get(key);
};
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/