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 124 commits
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,7 +1,7 @@
function spy(func) {

function wrapper(...args) {
// using ...args instead of arguments to store "real" array in wrapper.calls
// usando ...args ao invés de arguments para guardar o "verdadeiro" array dentro de wrapper.calls
wrapper.calls.push(args);
return func.apply(this, args);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
function spy(func) {
// your code
// o seu código
}


Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
describe("spy", function() {
it("records calls into its property", function() {
it("guarde as chamadas dentro da sua propriedade", function() {
function work() {}

work = spy(work);
Expand All @@ -17,7 +17,7 @@ describe("spy", function() {
]);
});

it("transparently wraps functions", function() {
it("encapsula transparentemente as funções", function() {

let sum = sinon.spy((a, b) => a + b);

Expand All @@ -28,7 +28,7 @@ describe("spy", function() {
});


it("transparently wraps methods", function() {
it("encapsula transparentemente os métodos", function() {

let calc = {
sum: sinon.spy((a, b) => a + b)
Expand Down
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 por `spy(f)` deve guardar todos os argumentos e depois 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.
Crie um decorador `spy(func)` que retorne um encapsulador que guarde todas as chamadas de uma função na sua propriedade `calls`.

Every call is saved as an array of arguments.
Todas as chamadas são guardadas num 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ários
}

*!*
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. Esse decorador é algumas vezes útil para testes unitários. Sua forma avançada é `sinon.spy` na biblioteca [Sinon.JS](http://sinonjs.org).
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ describe("delay", function() {
this.clock.restore();
});

it("calls the function after the specified timeout", function() {
it("chama a função depois do limite de tempo especificado", function() {
let start = Date.now();

function f(x) {
Expand All @@ -18,10 +18,10 @@ describe("delay", function() {
let f1000 = delay(f, 1000);
f1000("test");
this.clock.tick(2000);
assert(f.calledOnce, 'calledOnce check fails');
assert(f.calledOnce, 'A verificação do calledOnce falhou');
});

it("passes arguments and this", function() {
it("passa os argumentos e this", function() {
let start = Date.now();
let user = {
sayHi: function(phrase, who) {
Expand All @@ -41,6 +41,6 @@ describe("delay", function() {

this.clock.tick(2000);

assert(spy.calledOnce, 'calledOnce check failed');
assert(spy.calledOnce, 'A verificação do calledOnce falhou');
});
});
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,22 +11,22 @@ function delay(f, ms) {

let f1000 = delay(alert, 1000);

f1000("test"); // shows "test" after 1000ms
f1000("test"); // exibe "test" depois de 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 seta (arrow function) é usada aqui. Tal como sabemos, funções seta não têm seus próprios `this` e `arguments`, então `f.apply(this, arguments)` recebe `this` e `arguments` a partir do encapsulador.

If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (assuming we're in the browser).
Se passássemos uma função normal, `setTimeout` iria chamá-la sem argumentos nem `this=window` (assumindo que estávamos 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 intermédia, 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 numa variável intermédia
setTimeout(function() {
f.apply(savedThis, args); // use it here
f.apply(savedThis, args); // use-a aqui
}, ms);
};

Expand Down
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.
Crie um decorador `delay(f, ms)` que atrase 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"); // exibe "test" depois de 1000ms
f1500("test"); // exibe "test" depois de 1500ms
```

In other words, `delay(f, ms)` returns a "delayed by `ms`" variant of `f`.
Por 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 com um único argumento, porém a sua solução deve passar todos os argumentos e o `this` do contexto.
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,33 @@ describe('debounce', function () {
this.clock.restore();
});

it('for one call - runs it after given ms', function () {
it('para uma chamada - executa-o depois de dados milissegundos', function () {
const f = sinon.spy();
const debounced = debounce(f, 1000);

debounced('test');
assert(f.notCalled, 'not called immediately');
assert(f.notCalled, 'não é chamada imediatamente');
this.clock.tick(1000);
assert(f.calledOnceWith('test'), 'called after 1000ms');
assert(f.calledOnceWith('test'), 'é chamada depois de 1000ms');
});

it('for 3 calls - runs the last one after given ms', function () {
it('para 3 chamadas - execute a última depois de dados milissegundos', function () {
const f = sinon.spy();
const debounced = debounce(f, 1000);

debounced('a');
setTimeout(() => debounced('b'), 200); // ignored (too early)
setTimeout(() => debounced('c'), 500); // runs (1000 ms passed)
setTimeout(() => debounced('b'), 200); // ignorada (cedo demais)
setTimeout(() => debounced('c'), 500); // executa (1000ms passados)
this.clock.tick(1000);

assert(f.notCalled, 'not called after 1000ms');
assert(f.notCalled, 'não é chamada depois de 1000ms');

this.clock.tick(500);

assert(f.calledOnceWith('c'), 'called after 1500ms');
assert(f.calledOnceWith('c'), 'é chamada depois de 1500ms');
});

it('keeps the context of the call', function () {
it('preserva o contexto da chamada', function () {
let obj = {
f() {
assert.equal(this, obj);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<!doctype html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Function <code>handler</code> is called on this input:
A função <code>handler</code> é chamada neste campo de entrada:
<br>
<input id="input1" placeholder="type here">

<p>

Debounced function <code>debounce(handler, 1000)</code> is called on this input:
A função de debounce <code>debounce(handler, 1000)</code> é chamada neste campo de entrada:
<br>
<input id="input2" placeholder="type here">

<p>
<button id="result">The <code>handler</code> puts the result here</button>
<button id="result">O <code>handler</code> coloca o resultado aqui</button>

<script>
function handler(event) {
Expand All @@ -21,4 +21,4 @@

input1.oninput = handler;
input2.oninput = _.debounce(handler, 1000);
</script>
</script>
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 de `debounce` retorna um encapsulador. Quando chamada, ela agenda a chamada original da função depois de certos `ms` e cancela o tempo de espera (timeout) anterior.
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,50 @@ 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 de `f` até haver `ms` milissegundos de inactividade (nenhuma chamada, "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`).
Por outras palavras, `debounce` é como uma secretária que aceita "chamadas telefónicas", e espera até existirem `ms` milissegundos de inatividade. E, somente então transfere a informação da última chamada 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 por `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 for 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 após a última chamada.

![](debounce.svg)

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

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 código para isso (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")
// a função de debounce espera 1000ms após a última chamada e depois executa: alert("c")
```

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 o usuário digita alguma coisa, e gostaríamos de fazer um pedido ao servidor quando a entrada tiver terminado.

There's no point in sending the request for every character typed. Instead we'd like to wait, and then process the whole result.
Não adianta enviar um pedido por cada caractere digitado. Ao invés disso gostariamos de esperar, e então processar todo o resultado.

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.
Num navegador, nós podemos configurar um gerenciador de eventos -- uma função que é chamada em todas as alterações no campo de entrada. Normalmente, um gerenciador de eventos é chamado com frequência, a cada tecla pressionada. Porém, se nós fizermos o `debounce` dele por 1000ms, então ele será chamando apenas uma vez, depois de 1000ms após a última entrada.

```online

In this live example, the handler puts the result into a box below, try it:
Neste exemplo online, o gerenciador coloca o resultado na 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.
Você vê? A segunda entrada chama a função de debounce, assim o seu conteúdo será processado após 1000ms depois 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` é uma excelente maneira de processar uma sequência de eventos: seja ela uma sequência de teclas pressionadas, movimentos do rato ou alguma outra coisa.

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

The task is to implement `debounce` decorator.
A tarefa é 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ê estiver a pensar nisso :)
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ function throttle(func, ms) {
function wrapper() {

if (isThrottled) {
// memo last arguments to call after the cooldown
// memorizar os últimos argumentos para a chamada depois da espera
savedArgs = arguments;
savedThis = this;
return;
}

// otherwise go to cooldown state
// caso contrário vá para o estado de espera
func.apply(this, arguments);

isThrottled = true;

// plan to reset isThrottled after the delay
// planeia reinicializar isThrottled depois do atraso
setTimeout(function() {
isThrottled = false;
if (savedArgs) {
// if there were calls, savedThis/savedArgs have the last one
// recursive call runs the function and sets cooldown again
// se houver chamadas, savedThis/saveArgs tem a última
// a chamada recursiva executa a função e configura a espera novamente
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}

return wrapper;
}
}
Loading