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: 1-js/06-advanced-functions/09-call-apply-decorators/article.md
+7-9Lines changed: 7 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,9 +6,9 @@ JavaScript gives exceptional flexibility when dealing with functions. They can b
6
6
7
7
Let's say we have a function `slow(x)` which is CPU-heavy, but its results are stable. In other words, for the same `x` it always returns the same result.
8
8
9
-
If the function is called often, we may want to cache (remember) the results for different `x`to avoid spending extra-time on recalculations.
9
+
If the function is called often, we may want to cache (remember) the results to avoid spending extra-time on recalculations.
10
10
11
-
But instead of adding that functionality into `slow()` we'll create a wrapper. As we'll see, there are many benefits of doing so.
11
+
But instead of adding that functionality into `slow()` we'll create a wrapper function, that adds caching. As we'll see, there are many benefits of doing so.
12
12
13
13
Here's the code, and explanations follow:
14
14
@@ -23,13 +23,13 @@ function cachingDecorator(func) {
23
23
let cache =newMap();
24
24
25
25
returnfunction(x) {
26
-
if (cache.has(x)) { // if the result is in the map
27
-
returncache.get(x); //return it
26
+
if (cache.has(x)) { // if there's such key in cache
27
+
returncache.get(x); //read the result from it
28
28
}
29
29
30
-
let result =func(x); // otherwise call func
30
+
let result =func(x); // otherwise call func
31
31
32
-
cache.set(x, result); // and cache (remember) the result
32
+
cache.set(x, result); // and cache (remember) the result
33
33
return result;
34
34
};
35
35
}
@@ -49,13 +49,11 @@ The idea is that we can call `cachingDecorator` for any function, and it will re
49
49
50
50
By separating caching from the main function code we also keep the main code simpler.
51
51
52
-
Now let's get into details of how it works.
53
-
54
52
The result of `cachingDecorator(func)` is a "wrapper": `function(x)` that "wraps" the call of `func(x)` into caching logic:
55
53
56
54

57
55
58
-
As we can see, the wrapper returns the result of `func(x)` "as is". From an outside code, the wrapped `slow` function still does the same. It just got a caching aspect added to its behavior.
56
+
From an outside code, the wrapped `slow` function still does the same. It just got a caching aspect added to its behavior.
59
57
60
58
To summarize, there are several benefits of using a separate `cachingDecorator` instead of altering the code of `slow` itself:
0 commit comments