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
+25-25Lines changed: 25 additions & 25 deletions
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,20 @@
1
-
# Decorators and forwarding, call/apply
1
+
# Decoradores e reencaminhamento, chamar/aplicar
2
2
3
-
JavaScript gives exceptional flexibility when dealing with functions. They can be passed around, used as objects, and now we'll see how to *forward* calls between them and *decorate* them.
3
+
A JavaScript oferece uma flexibilidade excecional ao lidar com funções. Podem ser transmitidas, utilizadas como objetos, e agora veremos como *encaminhar* chamadas entre elas e *decorá-las*.
4
4
5
-
## Transparent caching
5
+
## Memorização transparente
6
6
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.
7
+
Digamos que temos uma função `slow(x)`que consume muito processamento, mas seus resultados são estáveis. Em outras palavras, para o mesmo`x`esta sempre retorna o mesmo resultado.
8
8
9
-
If the function is called often, we may want to cache (remember) the results to avoid spending extra-time on recalculations.
9
+
Se a função for chamada com frequência, podemos querer memorizar (lembrar) os resultados para evitar gastar tempo adicional em recálculos.
10
10
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.
11
+
Mas, em vez de adicionar essa funcionalidade em `slow()`criaremos uma função de embrulho, que adiciona a memorização. Como veremos, existem muitas vantagens em fazê-lo.
12
12
13
-
Here's the code, and explanations follow:
13
+
Eis o código, e as explicações que se seguem:
14
14
15
15
```js run
16
16
functionslow(x) {
17
-
//there can be a heavy CPU-intensive job here
17
+
//pode haver um processamento intensivo aqui
18
18
alert(`Called with ${x}`);
19
19
return x;
20
20
}
@@ -23,43 +23,43 @@ function cachingDecorator(func) {
23
23
let cache =newMap();
24
24
25
25
returnfunction(x) {
26
-
if (cache.has(x)) { //if there's such key in cache
27
-
returncache.get(x); //read the result from it
26
+
if (cache.has(x)) { //se existir tal chave na memória
27
+
returncache.get(x); //ler o resultado do mesmo
28
28
}
29
29
30
-
let result =func(x); //otherwise call func
30
+
let result =func(x); //caso contrário, chamar função
31
31
32
-
cache.set(x, result); //and cache (remember) the result
32
+
cache.set(x, result); //e memorizar (lembrar) o resultado
33
33
return result;
34
34
};
35
35
}
36
36
37
37
slow =cachingDecorator(slow);
38
38
39
-
alert( slow(1) ); // slow(1) is cached and the result returned
40
-
alert( "Again: "+slow(1) ); // slow(1) result returned from cache
39
+
alert( slow(1) ); // slow(1) é memorizado e o resultado retornado
40
+
alert( "Again: "+slow(1) ); //resultado da slow(1) retornado da memória
41
41
42
-
alert( slow(2) ); // slow(2) is cached and the result returned
43
-
alert( "Again: "+slow(2) ); // slow(2) result returned from cache
42
+
alert( slow(2) ); // slow(2) é memorizado e o resultado retornado
43
+
alert( "Again: "+slow(2) ); //resultado da slow(2) retornado da memória
44
44
```
45
45
46
-
In the code above `cachingDecorator`is a *decorator*: a special function that takes another function and alters its behavior.
46
+
No código acima `cachingDecorator`é um *decorador*: uma função especial que pega em outra função e altera o seu comportamento.
47
47
48
-
The idea is that we can call `cachingDecorator`for any function, and it will return the caching wrapper. That's great, because we can have many functions that could use such a feature, and all we need to do is to apply `cachingDecorator`to them.
48
+
A ideia é que podemos chamar `cachingDecorator`para qualquer função, e esta retornará o embrulho de memorização. Isto é ótimo, porque podemos ter muitas funções que poderiam usar esse recurso, e tudo o que precisamos fazer é aplicar `cachingDecorator`a elas.
49
49
50
-
By separating caching from the main function code we also keep the main code simpler.
50
+
Ao separar a memorização do código da função principal, também mantemos o código principal mais simples.
51
51
52
-
The result of `cachingDecorator(func)` is a "wrapper": `function(x)`that "wraps" the call of`func(x)`into caching logic:
52
+
O resultado de `caching` é um "embrulho": `function(x)`que "embrulha" a chama da`func(x)`na lógica de memorização:
53
53
54
54

55
55
56
-
From an outside code, the wrapped`slow`function still does the same. It just got a caching aspect added to its behavior.
56
+
A partir dum código externo, a função`slow`embrulhada ainda faz o mesmo. Esta apenas tem um aspeto de memorização adicionado ao seu comportamento.
57
57
58
-
To summarize, there are several benefits of using a separate `cachingDecorator`instead of altering the code of `slow`itself:
58
+
Para resumir, existem vários benefícios em utilizar um `cachingDecorator`separado ao invés de alterar o código da `slow`em si:
59
59
60
-
-The`cachingDecorator`is reusable. We can apply it to another function.
61
-
-The caching logic is separate, it did not increase the complexity of `slow`itself (if there was any).
62
-
-We can combine multiple decorators if needed (other decorators will follow).
60
+
-O`cachingDecorator`é reutilizável. Podemos aplicá-lo a outra função.
61
+
-A lógica de memorização é separada, não aumentou a complexidade da `slow`em si (se é que existia alguma).
62
+
-Podemos combinar vários decoradores, se necessário (outros decoradores seguir-se-ão).
0 commit comments