Skip to content

Commit 446154f

Browse files
committed
up
1 parent 02d1b76 commit 446154f

File tree

1 file changed

+7
-9
lines changed
  • 1-js/06-advanced-functions/09-call-apply-decorators

1 file changed

+7
-9
lines changed

1-js/06-advanced-functions/09-call-apply-decorators/article.md

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ JavaScript gives exceptional flexibility when dealing with functions. They can b
66

77
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.
88

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.
1010

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.
1212

1313
Here's the code, and explanations follow:
1414

@@ -23,13 +23,13 @@ function cachingDecorator(func) {
2323
let cache = new Map();
2424

2525
return function(x) {
26-
if (cache.has(x)) { // if the result is in the map
27-
return cache.get(x); // return it
26+
if (cache.has(x)) { // if there's such key in cache
27+
return cache.get(x); // read the result from it
2828
}
2929

30-
let result = func(x); // otherwise call func
30+
let result = func(x); // otherwise call func
3131

32-
cache.set(x, result); // and cache (remember) the result
32+
cache.set(x, result); // and cache (remember) the result
3333
return result;
3434
};
3535
}
@@ -49,13 +49,11 @@ The idea is that we can call `cachingDecorator` for any function, and it will re
4949

5050
By separating caching from the main function code we also keep the main code simpler.
5151

52-
Now let's get into details of how it works.
53-
5452
The result of `cachingDecorator(func)` is a "wrapper": `function(x)` that "wraps" the call of `func(x)` into caching logic:
5553

5654
![](decorator-makecaching-wrapper.svg)
5755

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.
5957

6058
To summarize, there are several benefits of using a separate `cachingDecorator` instead of altering the code of `slow` itself:
6159

0 commit comments

Comments
 (0)