Skip to content

Commit 925ff83

Browse files
authored
call-apply-decorators (#200)
1 parent 35999e5 commit 925ff83

File tree

11 files changed

+203
-203
lines changed

11 files changed

+203
-203
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
The wrapper returned by `spy(f)` should store all arguments and then use `f.apply` to forward the call.
1+
Обгортка, що повертається за допомогою `spy(f)`, повинна зберігати всі аргументи, а потім використовувати `f.apply`, щоб переадресувати виклик.

1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/task.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ importance: 5
22

33
---
44

5-
# Spy decorator
5+
# Декоратор-шпигун
66

7-
Create a decorator `spy(func)` that should return a wrapper that saves all calls to function in its `calls` property.
7+
Створіть декоратор `spy(func)`, який повинен повернути обгортку, яка зберігає всі виклики функції у властивості `calls`.
88

9-
Every call is saved as an array of arguments.
9+
Кожен виклик зберігається як масив аргументів.
1010

1111
For instance:
1212

1313
```js
1414
function work(a, b) {
15-
alert( a + b ); // work is an arbitrary function or method
15+
alert( a + b ); // працює як довільна функція або метод
1616
}
1717

1818
*!*
@@ -23,8 +23,8 @@ work(1, 2); // 3
2323
work(4, 5); // 9
2424

2525
for (let args of work.calls) {
26-
alert( 'call:' + args.join() ); // "call:1,2", "call:4,5"
26+
alert( 'виклик:' + args.join() ); // "виклик:1,2", "виклик:4,5"
2727
}
2828
```
2929

30-
P.S. That decorator is sometimes useful for unit-testing. Its advanced form is `sinon.spy` in [Sinon.JS](http://sinonjs.org/) library.
30+
P.S. Цей декоратор іноді корисний для unit-тестування. Його просунута форма -- `sinon.spy` у бібліотеці [Sinon.JS](http://sinonjs.org/).

1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The solution:
1+
Рішення:
22

33
```js run demo
44
function delay(f, ms) {
@@ -11,22 +11,22 @@ function delay(f, ms) {
1111

1212
let f1000 = delay(alert, 1000);
1313

14-
f1000("test"); // shows "test" after 1000ms
14+
f1000("тест"); // показує "тест" після 1000 мс
1515
```
1616

17-
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.
17+
Зверніть увагу, як тут використовується стрілочна функція. Як відомо, стрілочні функції не мають власних `this` та `arguments`, тому `f.apply(this, arguments)` бере `this` та `arguments` з обгортки.
1818

19-
If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (assuming we're in the browser).
19+
Якщо ми передамо звичайну функцію, `setTimeout` буде викликати її без аргументів, а `this=window` (припускаючи, що ми знаходимося в браузері).
2020

21-
We still can pass the right `this` by using an intermediate variable, but that's a little bit more cumbersome:
21+
Ми все ще можемо передати право `this` за допомогою проміжної змінної, але це трохи більше громіздко:
2222

2323
```js
2424
function delay(f, ms) {
2525

2626
return function(...args) {
27-
let savedThis = this; // store this into an intermediate variable
27+
let savedThis = this; // зберігаємо this в проміжну змінну
2828
setTimeout(function() {
29-
f.apply(savedThis, args); // use it here
29+
f.apply(savedThis, args); // використовуємо її тут
3030
}, ms);
3131
};
3232

1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,25 @@ importance: 5
22

33
---
44

5-
# Delaying decorator
5+
# Затримуючий декоратор
66

7-
Create a decorator `delay(f, ms)` that delays each call of `f` by `ms` milliseconds.
7+
Створіть декоратор `delay(f, ms)`, яка затримує кожен виклик `f` на `ms` мілісекунд.
88

9-
For instance:
9+
Наприклад:
1010

1111
```js
1212
function f(x) {
1313
alert(x);
1414
}
1515

16-
// create wrappers
16+
// створюємо обгортки
1717
let f1000 = delay(f, 1000);
1818
let f1500 = delay(f, 1500);
1919

20-
f1000("test"); // shows "test" after 1000ms
21-
f1500("test"); // shows "test" after 1500ms
20+
f1000("тест"); // показує "test" після 1000 мс
21+
f1500("тест"); // показує "test" після 1500 мс
2222
```
2323

24-
In other words, `delay(f, ms)` returns a "delayed by `ms`" variant of `f`.
24+
Іншими словами, `delay(f, ms)` повертає варіант `f` з "затримкою на `ms`".
2525

26-
In the code above, `f` is a function of a single argument, but your solution should pass all arguments and the context `this`.
26+
У коді вище, `f` є функцією одного аргументу, але ваше рішення повинно передавати всі аргументи та контекст `this`.
Lines changed: 1 addition & 1 deletion
Loading

1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ function debounce(func, ms) {
99

1010
```
1111

12-
A call to `debounce` returns a wrapper. When called, it schedules the original function call after given `ms` and cancels the previous such timeout.
12+
Виклик `debounce` повертає обгортку. Коли він викликається, він відкладає виклик оригінальної функції після даного `ms` і скасовує попередній подібний тайм-аут.
1313

1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/task.md

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,50 +2,50 @@ importance: 5
22

33
---
44

5-
# Debounce decorator
5+
# Декоратор debounce
66

7-
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.
7+
Результат `debounce(f, ms)` декоратору -- це обгортка, що призупиняє виклики до `f`, поки не пройде `ms` мілісекунд бездіяльності (без викликів, "cooldown period"), а потім викликає `f` один раз з останніми аргументами.
88

9-
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`).
9+
Іншими словами, `debounce` -- це як секретар, який приймає "телефонні дзвінки", і чекає, поки не закінчаться `ms` мілісекунди тиші. І лише тоді він передає останню інформацію про виклик до "боса" (викликає фактичну `f`).
1010

11-
For instance, we had a function `f` and replaced it with `f = debounce(f, 1000)`.
11+
Наприклад, у нас була функція `f` і замінили її на `f = debounce(f, 1000)`.
1212

13-
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.
13+
Тоді, якщо загорнута функція викликається при 0 мс, 200 мс та 500 мс, а потім викликів немає, то фактична `f` буде викликатися лише один раз, при 1500 мс. Тобто: після закінчення періоду 1000 мс від останнього виклику.
1414

1515
![](debounce.svg)
1616

17-
...And it will get the arguments of the very last call, other calls are ignored.
17+
...І вона отримає аргументи самого останнього виклику, а інші виклики будуть ігноруватися.
1818

19-
Here's the code for it (uses the debounce decorator from the [Lodash library](https://lodash.com/docs/4.17.15#debounce)):
19+
Ось код для цього (використовує декоратор debounce з [Lodash library](https://lodash.com/docs/4.17.15#debounce)):
2020

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

2424
f("a");
2525
setTimeout( () => f("b"), 200);
2626
setTimeout( () => f("c"), 500);
27-
// debounced function waits 1000ms after the last call and then runs: alert("c")
27+
// повернута з debounced функція чекає 1000 мс після останнього виклику, а потім запускає: alert("c")
2828
```
2929

30-
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.
30+
Тепер практичний приклад. Скажімо, користувач друкує щось, і ми хотіли б надіслати запит на сервер, коли ввід закінчиться.
3131

32-
There's no point in sending the request for every character typed. Instead we'd like to wait, and then process the whole result.
32+
Немає сенсу надсилати запит на кожен набраний символ. Замість цього ми хотіли б почекати, а потім обробляти весь результат.
3333

34-
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.
34+
У веббраузері ми можемо налаштувати обробник подій -- функцію, яка викликається при кожній зміні поля введення.Зазвичай, обробник подій викликається дуже часто, для кожного друкованого символу. Але якщо ми використаємо `debounce` на 1000 мс, то він буде викликатися лише один раз, через 1000 мс після останнього введення.
3535

3636
```online
3737
38-
In this live example, the handler puts the result into a box below, try it:
38+
У цьому реальному прикладі обробник ставить результат у поле нижче, спробуйте це:
3939
4040
[iframe border=1 src="debounce" height=200]
4141
42-
See? The second input calls the debounced function, so its content is processed after 1000ms from the last input.
42+
Бачите? Другий ввід викликає функцію, що була повернута з `debounce`, тому цей вміст обробляється через 1000 мс з останнього введення.
4343
```
4444

45-
So, `debounce` is a great way to process a sequence of events: be it a sequence of key presses, mouse movements or something else.
45+
Отже, `debounce` -- це чудовий спосіб обробки послідовності подій: будь то послідовність натискання клавіш, рухів миші або щось інше.
4646

47-
It waits the given time after the last call, and then runs its function, that can process the result.
47+
Він чекає певного часу після останнього дзвінка, а потім запускає свою функцію, яка може обробити результат.
4848

49-
The task is to implement `debounce` decorator.
49+
Завдання полягає в тому, щоб реалізувати декоратор `debounce`.
5050

51-
Hint: that's just a few lines if you think about it :)
51+
Підказка: Це лише кілька рядків, якщо ви думаєте про це :)

0 commit comments

Comments
 (0)