You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: L-A/0014 Memoize II/README.md
+15Lines changed: 15 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -52,3 +52,18 @@ Merging two empty objects will always result in an empty object. The 2nd and 3rd
52
52
0 <= inputs.flat().length <= 105
53
53
inputs[i][j] != NaN
54
54
```
55
+
56
+
## Approach:
57
+
Map is perfect for storing single argument. Each consecutive argument must have cache based on previous argument, which will form a tree like structure, like this:
58
+
```javascript
59
+
fn(1,3,4) // { 1: { 3: { 4: {}}}};
60
+
fn(1,4,3) // { 1: { 3: { 4: {}}, 4: { 3: {}}}};
61
+
```
62
+
The only problem, is how do we store our result. It's been never stated, that memoized function will be called with the same amount of arguments every time. We need a way to store our result anywhere on the path and also make sure that it will never be misteaken with argument. Here is example.
63
+
```javascript
64
+
fn(1,3) // { 1: { 3: 4}};
65
+
-> 4
66
+
fn(1) // { 1: { 3: 4}};
67
+
-> { 3:4 } // returning cache branch as result
68
+
```
69
+
There are different aproaches to overcome this. But since every Symbol() call is guaranteed to return a unique Symbol we can use it to store actual result with guarantee, that it will never match any argument.
0 commit comments