Skip to content

Decorators and forwarding, call/apply #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
139 commits
Select commit Hold shift + click to select a range
6f24e24
add portuguese translations for 09-call-apply-decorators
nazarepiedady Jul 20, 2021
f61fc2a
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 24, 2021
75233f9
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 24, 2021
df22c3a
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 24, 2021
f791dc2
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 24, 2021
f21bfd1
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 24, 2021
ed2891f
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
e81827a
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 24, 2021
5a1d081
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 24, 2021
65061ee
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
a940f62
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
beb803e
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
8daf648
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
e035343
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
e64df68
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 24, 2021
2ac8f34
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 24, 2021
1fe7c8e
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 24, 2021
6ec0c37
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
27720a9
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
3c51f58
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
019f8c7
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
470c042
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
2424a49
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
373d7de
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
f4eb016
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
28db3ae
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
fc60987
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 24, 2021
31c7c26
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
9922f99
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 24, 2021
ce1c564
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
20201dd
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
79cb3d9
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
fe0ac71
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
e44b0a2
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
5408986
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
5a7fb16
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
febace3
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
2a1a6cc
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
a821f52
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
0e02ffa
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
e18716d
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
6fb0673
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
26310a2
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
60dd4ea
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
960a729
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 24, 2021
5b97fc8
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
3351efc
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
08b2eb7
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
94d26d6
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
42c670d
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
30ae0a0
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
3265629
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
7267678
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
f3e93b3
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
b5625b9
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
ed8f906
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
045b955
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
a0fe4a0
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
3d31814
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
2f07e4b
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
bf58b55
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
3303ae5
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
fb1db91
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
0493aa4
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
73f53ea
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
741ff03
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 24, 2021
049b00d
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 24, 2021
da7eff1
Apply suggestions from code review
nazarepiedady Jul 24, 2021
f98ef4b
translate to portuguese debounce.view/index.html
nazarepiedady Jul 24, 2021
8b3c159
Update task.md
odsantos Jul 25, 2021
d16f1fa
Add a blank line.
odsantos Jul 26, 2021
50cd890
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 26, 2021
08c2184
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 26, 2021
8c800bd
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 26, 2021
4ec2b71
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 26, 2021
9034888
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 26, 2021
17d85a6
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 26, 2021
193db3c
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 26, 2021
034ee04
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 26, 2021
1f12b61
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Jul 26, 2021
fa16310
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
1eab016
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
d5c26ae
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
b492500
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
f483b32
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
11f826b
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
833f4b0
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
8f77aa3
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
8865725
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
1dad4e7
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
8434772
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 26, 2021
8e0dae4
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 26, 2021
2337bb9
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 26, 2021
c32f813
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/t…
nazarepiedady Jul 26, 2021
bf26d67
Add space for untranslated line.
odsantos Jul 27, 2021
0d241d6
Add untranslated line.
odsantos Jul 27, 2021
18e8949
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Jul 28, 2021
029fe81
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/s…
nazarepiedady Jul 28, 2021
d13f456
translate the scripts into 4-throttle folder
nazarepiedady Jul 28, 2021
0b65ff8
translate the scripts into 3-debounce folder
nazarepiedady Jul 28, 2021
1ad0da4
translate the scripts into 01-spy-decorator folder
nazarepiedady Jul 28, 2021
deb74e8
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 29, 2021
2ddace6
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 29, 2021
c86916e
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Jul 29, 2021
fdb8eb2
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 29, 2021
71a229f
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 29, 2021
fbfd1a0
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 29, 2021
16a516b
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Jul 29, 2021
3fe9057
complete translations that are not completed
nazarepiedady Jul 29, 2021
41512ab
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Aug 2, 2021
af56b83
Update 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_…
nazarepiedady Aug 4, 2021
55e6731
Update 1-js/06-advanced-functions/09-call-apply-decorators/01-spy-dec…
nazarepiedady Aug 4, 2021
c6148f9
Update 1-js/06-advanced-functions/09-call-apply-decorators/03-debounc…
nazarepiedady Aug 4, 2021
d05874c
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Aug 4, 2021
c4a1750
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
3996f37
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
23b6c11
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
7969605
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
9bf4f1f
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
b1da41a
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Aug 4, 2021
fd1e970
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Aug 4, 2021
dc5e050
Update 1-js/06-advanced-functions/09-call-apply-decorators/article.md
nazarepiedady Aug 4, 2021
9f06223
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Aug 4, 2021
b126223
Update 1-js/06-advanced-functions/09-call-apply-decorators/04-throttl…
nazarepiedady Aug 4, 2021
2deb617
docs: update `call-apply-decorators/throttle` article
nazarepiedady Mar 5, 2024
553b999
docs: update `call-apply-decorators/debounce` article
nazarepiedady Mar 5, 2024
58420f8
docs: update `call-apply-decorators/delay` article
nazarepiedady Mar 5, 2024
626cf58
docs: update `call-apply-decorators/debounce/debounce.svg`
nazarepiedady Mar 5, 2024
bf3e634
docs: update `call-apply-decorators/decorator-makecaching-wrapper.svg`
nazarepiedady Mar 5, 2024
07f5a47
docs: update `call-apply-decorators/spy-decorator` article
nazarepiedady Mar 15, 2024
5a2cc59
docs: update `call-apply-decorators/article.md` english content
nazarepiedady Mar 15, 2024
8fc6d38
docs: translate the first two section of `call-apply-decorators/artic…
nazarepiedady Mar 15, 2024
23ed1bf
docs: translate one more piece of `call-apply-decorators` article
nazarepiedady Mar 16, 2024
fe966ce
docs: translate one more piece of `call-apply-decorators` article
nazarepiedady Mar 17, 2024
a75c9f4
docs: finish the translation of `call-apply-decorators` article
nazarepiedady Mar 18, 2024
00481c7
Merge branch 'master' into decorators-forwarding-call-apply
nazarepiedady Mar 18, 2024
79b2b8c
docs: update `call-apply-decorators/spy-decorator/task.md`
nazarepiedady Mar 24, 2024
f60fbb7
docs: update `call-apply-decorators/delay/solution.md`
nazarepiedady Mar 24, 2024
9f2d639
docs: update `call-apply-decorators/spy-decorator/task.md`
nazarepiedady Mar 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1 @@
The wrapper returned by `spy(f)` should store all arguments and then use `f.apply` to forward the call.
O encapsulador retornado pelo `spy(f)` deve guardar todos argumentos e então usar `f.apply` para encaminhar a chamada.
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Spy decorator
# Decorador Spy (espião)

Create a decorator `spy(func)` that should return a wrapper that saves all calls to function in its `calls` property.
Criar um decorador `spy(func)` que deve retornar um encapsulador que guarda todas chamadas de uma função em sua propriedade `calls`.

Every call is saved as an array of arguments.
Todas chamadas são guardadas como um array de argumentos.

For instance:
Por exemplo:

```js
function work(a, b) {
alert( a + b ); // work is an arbitrary function or method
alert( a + b ); // work é uma função ou método arbitrário
}

*!*
Expand All @@ -27,4 +27,4 @@ for (let args of work.calls) {
}
```

P.S. That decorator is sometimes useful for unit-testing. Its advanced form is `sinon.spy` in [Sinon.JS](http://sinonjs.org/) library.
P.S. Que o decorador é algumas vezes útil para teste unitário. Sua forma avançada é `sinon.spy` na biblioteca [Sinon.JS](http://sinonjs.org).
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution:
A solução:

```js run demo
function delay(f, ms) {
Expand All @@ -11,24 +11,24 @@ function delay(f, ms) {

let f1000 = delay(alert, 1000);

f1000("test"); // shows "test" after 1000ms
f1000("test"); // imprima "test" depois 1000ms
```

Please note how an arrow function is used here. As we know, arrow functions do not have own `this` and `arguments`, so `f.apply(this, arguments)` takes `this` and `arguments` from the wrapper.
Por favor note como uma função em seta (arrow function) é usada aqui. Tal como sabemos, funções em setas não tem seu próprio `this` e `arguments`, então `f.apply(this, arguments)` recebem `this` e `arguments` a partir de um encapsulador.

If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (assuming we're in the browser).
Se passassemos uma função normal, `setTimeout` a chamaria sem argumentos e `this=window` (assumindo que estamos no browser).

We still can pass the right `this` by using an intermediate variable, but that's a little bit more cumbersome:
Ainda podemos passar o `this` certo atráves do uso de uma variável intermediador, porém é um pouco mais difícil:

```js
function delay(f, ms) {

return function(...args) {
let savedThis = this; // store this into an intermediate variable
let savedThis = this; // guarde isto dentro de uma variável intermediador
setTimeout(function() {
f.apply(savedThis, args); // use it here
f.apply(savedThis, args); // use-o aqui
}, ms);
};

}
```
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@ importance: 5

---

# Delaying decorator
# Atrasando o decorador

Create a decorator `delay(f, ms)` that delays each call of `f` by `ms` milliseconds.
Criar um decorador `delay(f, ms)` que atrasa cada chamada de `f` por `ms` milissegundos.

For instance:
Por exemplo:

```js
function f(x) {
alert(x);
}

// create wrappers
// cria encapsuladores
let f1000 = delay(f, 1000);
let f1500 = delay(f, 1500);

f1000("test"); // shows "test" after 1000ms
f1500("test"); // shows "test" after 1500ms
f1000("test"); // imprima "test" depois 1000ms
f1500("test"); // imprima "test" depois 1500ms
```

In other words, `delay(f, ms)` returns a "delayed by `ms`" variant of `f`.
Em outras palavras, `delay(f, ms)` retorna uma variante de `f` "atrasada em `ms`".

In the code above, `f` is a function of a single argument, but your solution should pass all arguments and the context `this`.
No código acima, `f` é uma função de um único argumento, porém sua solução deve passar todos argumentos e o contexto `this`.
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ function debounce(func, ms) {

```

A call to `debounce` returns a wrapper. When called, it schedules the original function call after given `ms` and cancels the previous such timeout.

Uma chamada para `debounce` retorna um encapsulador. Quando chamado, ela agenda a função original chama depois de receber `ms` e cancela o tempo limite anterior.
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,51 @@ importance: 5

---

# Debounce decorator
# O Decorador Debounce

The result of `debounce(f, ms)` decorator is a wrapper that suspends calls to `f` until there's `ms` milliseconds of inactivity (no calls, "cooldown period"), then invokes `f` once with the latest arguments.
O resultado do decorador `debounce(f, ms)` é um encapsulador que suspende chamadas para `f` até haver `ms` milissegundos de inactividade (sem chamadas, "período de espera"), depois invoca `f` uma vez com os últimos argumentos.

In other words, `debounce` is like a secretary that accepts "phone calls", and waits until there's `ms` milliseconds of being quiet. And only then it transfers the latest call information to "the boss" (calls the actual `f`).
Em outras palavras, `debounce` é como uma secretária que aceita "chamadas de telefones", e espera até existir `ms` milissegundos de espera. E somente então transferir as últimas informações de chamadas para "o chefe" (chama a `f` atual).

For instance, we had a function `f` and replaced it with `f = debounce(f, 1000)`.
Por exemplo, tinhamos uma função `f` e a substituimos com `f = debounce(f, 1000)`.

Then if the wrapped function is called at 0ms, 200ms and 500ms, and then there are no calls, then the actual `f` will be only called once, at 1500ms. That is: after the cooldown period of 1000ms from the last call.
Então se a função encapsulada é chamada aos 0ms, 200ms, e 500ms, e depois não houver chamadas, a `f` atual será somente chamada uma vez, aos 1500ms. Ou seja: depois do período de espera de 1000ms da última chamada.

![](debounce.svg)

...And it will get the arguments of the very last call, other calls are ignored.
...E receberão os argumentos de toda última chamada, outras chamadas são ignorada.

Here's the code for it (uses the debounce decorator from the [Lodash library](https://lodash.com/docs/4.17.15#debounce)):
Aqui estão o código para isto (que usa o decorador debounce da [biblioteca Lodash](https://lodash.com/docs/4.17.15#debounce)):

```js
let f = _.debounce(alert, 1000);

f("a");
setTimeout( () => f("b"), 200);
setTimeout( () => f("c"), 500);
// debounced function waits 1000ms after the last call and then runs: alert("c")
// função tratada pelo debounce espera 1000ms depois da última chamada e depois executa: alert("*")
```

Now a practical example. Let's say, the user types something, and we'd like to send a request to the server when the input is finished.
Agora um exemplo prático. Vamos dizer, que usuário digite alguma coisa, e gostariamos enviar uma requisição para o servidor quando a entrada estiver terminda.

There's no point in sending the request for every character typed. Instead we'd like to wait, and then process the whole result.

In a web-browser, we can setup an event handler -- a function that's called on every change of an input field. Normally, an event handler is called very often, for every typed key. But if we `debounce` it by 1000ms, then it will be only called once, after 1000ms after the last input.
Não adianta enviar uma requesição para character digitado. Ao invés disso gostariamos de esperar, e depois processar todo resultado.

Em um web-browser, nós podemos configurar um manipulador de evento -- uma função que é chamada em todas mundanças no campo de entrada. Normalmente, um manipulador de evento é chamado sempre, para toda tecla pressionada. Porém se nós `debounce` ela por 1000ms, logo ela será chamanda apenas uma vez, depois 1000ms depois da última entrada.

```online

In this live example, the handler puts the result into a box below, try it:
Neste exemplo funcionando, o manipulador coloca o resultado dentro da caixa abaixo, experimente:

[iframe border=1 src="debounce" height=200]

See? The second input calls the debounced function, so its content is processed after 1000ms from the last input.
Vês? A segunda entrada chama a função na qual foi aplicada o debounce, então o seu conteúdo será processado depois de 1000ms da última entrada.
```

So, `debounce` is a great way to process a sequence of events: be it a sequence of key presses, mouse movements or something else.
Portanto, `debounce` é excelente maneira de processar uma sequência de eventos: seja ela uma sequência de pressões de teclas, movimentos de mouse ou alguma coisa do genero.

It waits the given time after the last call, and then runs its function, that can process the result.
Isto espera o tempo dado depois da última chamada, e depois executa sua função, que pode processar o resultado.

The task is to implement `debounce` decorator.
A tarefa está em implementar o decorador `debounce`.

Hint: that's just a few lines if you think about it :)
Dica: são apenas uma poucas linhas se você pensar sobre ela :)
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ function throttle(func, ms) {
}
```

A call to `throttle(func, ms)` returns `wrapper`.
Uma chamada para `throttle(func, ms` retorna `wrapper`.

1. During the first call, the `wrapper` just runs `func` and sets the cooldown state (`isThrottled = true`).
2. In this state all calls are memorized in `savedArgs/savedThis`. Please note that both the context and the arguments are equally important and should be memorized. We need them simultaneously to reproduce the call.
3. After `ms` milliseconds pass, `setTimeout` triggers. The cooldown state is removed (`isThrottled = false`) and, if we had ignored calls, `wrapper` is executed with the last memorized arguments and context.
1. Durante a primeira chamada, o `wrapper` apenas executa a `func` e configura o estado de espera (`isThrottled = true`).
2. Neste estado todas as chamadas são memorizadas em `savedArgs/savedThis`. Note que ambos o contexto e os argumentos são igualmente importante e devem ser memorizado. Nós precisamos deles simultaneamente reproduzir a chamada.
3. Depois `ms` milissegundos passam, `setTimeout` é acionada. O estado de espera é removido (`isThrottled = false`) e, se nós tivemos ignorado as chamadas, `wrapper` é executado com os últimos argumentos e contexto memorizados.

The 3rd step runs not `func`, but `wrapper`, because we not only need to execute `func`, but once again enter the cooldown state and setup the timeout to reset it.
O terceiro passo executa não `func`, mas o `wrapper`, porque nós não só precisamos executar o `func`, mas mais uma vez, entra no estado de espera e configura o tempo limite para reconfigurá-lo.
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,52 @@ importance: 5

---

# Throttle decorator
# O Decorador Throttle

Create a "throttling" decorator `throttle(f, ms)` -- that returns a wrapper.
Crie um decorador de "throttling" `throttle(f, ms)` -- que retorna um encapsulador.

When it's called multiple times, it passes the call to `f` at maximum once per `ms` milliseconds.
Quando é chamada várias vezes, ela passa a chamada para `f` no máximo uma vez por `ms` milissegundos.

The difference with debounce is that it's completely different decorator:
- `debounce` runs the function once after the "cooldown" period. Good for processing the final result.
- `throttle` runs it not more often than given `ms` time. Good for regular updates that shouldn't be very often.
A diferença com debounce é que é um decorador completamente diferente:
- `debounce` executa a função uma vez depois do período de "espera". Boa para o processamento final do resultado.
- `throttle` executa-o não mais frequentemente do que no tempo `ms` determinado.

In other words, `throttle` is like a secretary that accepts phone calls, but bothers the boss (calls the actual `f`) not more often than once per `ms` milliseconds.
Em outras palavras, `throttle` é como uma secretária que aceita chamadas de telefone, mas incomonda o chefe (chama `f` atual) não mais do que uma vez por`ms` milissegundos.

Let's check the real-life application to better understand that requirement and to see where it comes from.
Vamos verificar a aplicação na vida real para melhor entender esse requesito e ver de onde ela vem.

**For instance, we want to track mouse movements.**
**Por exemplo, queremos rastrear os movimentos do mouse**

In a browser we can setup a function to run at every mouse movement and get the pointer location as it moves. During an active mouse usage, this function usually runs very frequently, can be something like 100 times per second (every 10 ms).
**We'd like to update some information on the web-page when the pointer moves.**
Em um browser nós podemos configurar uma função para executar em todo movimento do mouse e receber a localização do ponteiro conforme ele se move. Durante o uso constante do mouse, esta função geralmente é executada com muita frequência, pode ser algo como 100 vezes por segundo (a cada 10 ms).
**Gostariamos de atualizar algumas informações na página web sempre que o ponteiro se mover.**

Updating function `update()` is too heavy to do it on every micro-movement. There is also no sense in making it more often than once per 100ms.
A atualização da função `update()` é uma tarefa muito pesada de se fazer em todo micro-movimento. Também não há sentido em fazer isso mais do que uma vez por 100ms.

So we'll assign `throttle(update, 100)` as the function to run on each mouse move instead of the original `update()`. The decorator will be called often, but `update()` will be called at maximum once per 100ms.
Portanto, vamos atribuir `throttle(update, 100)` como a função a ser executar em cada movimento de mouse ao invés do `update()` original. O decorador será chamada sempre, porém o `update()` será chamado no máximo uma vez por 100ms.

Visually, it will look like this:
Visualmente, ela parecerá com algo como isso:

1. For the first mouse movement the decorated variant passes the call to `update`. That's important, the user sees our reaction to their move immediately.
2. Then as the mouse moves on, until `100ms` nothing happens. The decorated variant ignores calls.
3. At the end of `100ms` -- one more `update` happens with the last coordinates.
4. Then, finally, the mouse stops somewhere. The decorated variant waits until `100ms` expire and then runs `update` with last coordinates. So, perhaps the most important, the final mouse coordinates are processed.
1. Para o primeiro movimento do mouse a variante decorada passa a chamada para `update`. É importante, os usuários verem nossa reação aos seus movimentos imediatamente.
2. Assim ao mover o mouse, até `100ms` nada acontece. A variante decorada é ignora chamadas.
3. Ao final de `100ms` -- mais um `update` acontece com as últimas coordenadas.
4. Assim, finalmente, o mouse para em algum lugar. A variante decorada espera até `100ms` expirar e depois executa o `update` com as últimas coordinadas. Então, talvez o mais importante, a coordenadas finais do mouse são processadas.

A code example:
Um código de exemplo:

```js
function f(a) {
console.log(a);
}

// f1000 passes calls to f at maximum once per 1000 ms
// f1000 passa a chamada para f no máximo uma vez por 1000ms
let f1000 = throttle(f, 1000);

f1000(1); // shows 1
f1000(2); // (throttling, 1000ms not out yet)
f1000(3); // (throttling, 1000ms not out yet)
f1000(1); // exibi 1
f1000(2); // (throttling, 1000ms ainda não saiu)
f1000(3); // (throttling, 1000ms ainda não saiu)

// when 1000 ms time out...
// ...outputs 3, intermediate value 2 was ignored
// quando o tempo de 1000ms estiver esgotado...
// ...exibi 3, o valor intermediário 2 foi ignorado
```

P.S. Arguments and the context `this` passed to `f1000` should be passed to the original `f`.
P.S. Os argumentos e o contexto `this` passados para `f1000` devem ser passados para a função original `f`.
Loading