forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2630-memoize-ii.js
More file actions
30 lines (29 loc) · 866 Bytes
/
2630-memoize-ii.js
File metadata and controls
30 lines (29 loc) · 866 Bytes
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
/**
* 2630. Memoize II
* https://leetcode.com/problems/memoize-ii/
* Difficulty: Hard
*
* 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.
*/
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const cache = {};
const idLookup = new Map();
function generateId(item) {
return idLookup.get(item) ?? idLookup.set(item, idLookup.size + 1).get(item);
}
return (...args) => {
const key = args.map(generateId).join('-');
return !cache.hasOwnProperty(key) ? (cache[key] = fn(...args)) : cache[key];
};
}