|
| 1 | +2630\. Memoize II |
| 2 | + |
| 3 | +Hard |
| 4 | + |
| 5 | +Given a function `fn`, return a **memoized** version of that function. |
| 6 | + |
| 7 | +A **memoized **function is a function that will never be called twice with the same inputs. Instead it will return a cached value. |
| 8 | + |
| 9 | +`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. |
| 10 | + |
| 11 | +**Example 1:** |
| 12 | + |
| 13 | +**Input:** |
| 14 | + |
| 15 | +getInputs = () => [[2,2],[2,2],[1,2]] |
| 16 | + |
| 17 | +fn = function (a, b) { return a + b; } |
| 18 | + |
| 19 | +**Output:** [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}] |
| 20 | + |
| 21 | +**Explanation:** |
| 22 | + |
| 23 | + const inputs = getInputs(); |
| 24 | + const memoized = memoize(fn); |
| 25 | + for (const arr of inputs) { |
| 26 | + memoized(...arr); |
| 27 | + } |
| 28 | + |
| 29 | +For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn(). |
| 30 | + |
| 31 | +For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required. |
| 32 | + |
| 33 | +For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2. |
| 34 | + |
| 35 | +**Example 2:** |
| 36 | + |
| 37 | +**Input:** |
| 38 | + |
| 39 | +getInputs = () => [[{},{}],[{},{}],[{},{}]] |
| 40 | + |
| 41 | +fn = function (a, b) { return ({...a, ...b}); } |
| 42 | + |
| 43 | +**Output:** [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}] |
| 44 | + |
| 45 | +**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. |
| 46 | + |
| 47 | +**Example 3:** |
| 48 | + |
| 49 | +**Input:** |
| 50 | + |
| 51 | +getInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; } |
| 52 | + |
| 53 | +fn = function (a, b) { return ({...a, ...b}); } |
| 54 | + |
| 55 | +**Output:** [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}] |
| 56 | + |
| 57 | +**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. |
| 58 | + |
| 59 | +**Constraints:** |
| 60 | + |
| 61 | +* <code>1 <= inputs.length <= 10<sup>5</sup></code> |
| 62 | +* <code>0 <= inputs.flat().length <= 10<sup>5</sup></code> |
| 63 | +* `inputs[i][j] != NaN` |
0 commit comments