Skip to content

Function object, NFE #198

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
merged 22 commits into from
Sep 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
8a5ab06
function-object
MykolaSopiha Sep 4, 2021
b4c9f9f
function-object
MykolaSopiha Sep 4, 2021
7e792a6
function-object
MykolaSopiha Sep 11, 2021
836c408
function-object
MykolaSopiha Sep 11, 2021
f84c353
function-object
MykolaSopiha Sep 11, 2021
76ba9df
function-object
MykolaSopiha Sep 11, 2021
8ea92d8
function-object
MykolaSopiha Sep 11, 2021
848a163
function-object
MykolaSopiha Sep 11, 2021
e5d98d8
Update 1-js/06-advanced-functions/06-function-object/2-counter-inc-de…
MykolaSopiha Sep 13, 2021
d53d5f9
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
MykolaSopiha Sep 13, 2021
fb61ef8
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
MykolaSopiha Sep 13, 2021
8c438ff
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
MykolaSopiha Sep 13, 2021
fa8ae01
Update 1-js/06-advanced-functions/06-function-object/article.md
MykolaSopiha Sep 13, 2021
b9602bd
Update 1-js/06-advanced-functions/06-function-object/article.md
MykolaSopiha Sep 13, 2021
bf2f942
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
MykolaSopiha Sep 13, 2021
3f73e08
Update 1-js/06-advanced-functions/06-function-object/article.md
MykolaSopiha Sep 13, 2021
0d08ac0
function-object
MykolaSopiha Sep 13, 2021
8f2a963
Merge branch 'function-object' of github.com:MykolaSopiha/uk.javascri…
MykolaSopiha Sep 13, 2021
177060e
function-object
MykolaSopiha Sep 13, 2021
2231004
function-object
MykolaSopiha Sep 13, 2021
9e1033e
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
tarasyyyk Sep 13, 2021
bde190b
Update 1-js/06-advanced-functions/06-function-object/5-sum-many-brack…
tarasyyyk Sep 13, 2021
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,2 +1,2 @@

The solution uses `count` in the local variable, but addition methods are written right into the `counter`. They share the same outer lexical environment and also can access the current `count`.
В рішенні використовується `count` у локальній змінній, але методи додавання записуються прямо в `counter`. Вони поділяють таке ж зовнішнє лексичне середовище, а також можуть отримати доступ до поточного `count`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ importance: 5

---

# Set and decrease for counter
# Встановити і зменшити лічильник

Modify the code of `makeCounter()` so that the counter can also decrease and set the number:
Змініть код `makeCounter()` так, щоб лічильник міг також зменшити та встановити рахунок:

- `counter()` should return the next number (as before).
- `counter.set(value)` should set the counter to `value`.
- `counter.decrease()` should decrease the counter by 1.
- `counter()` повинен повернути наступний рахунок (як раніше).
- `counter.set(value)` повинен встановити лічильник в значення `value`.
- `counter.decrease()` повинен зменшити лічильник на 1.

See the sandbox code for the complete usage example.
Див. код пісочниці з повним прикладом використання.

P.S. You can use either a closure or the function property to keep the current count. Or write both variants.
P.S. Ви можете використовувати або замикання, або властивість функції, щоб зберегти поточний рахунок. Або напишіть обидва варіанти.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

1. For the whole thing to work *anyhow*, the result of `sum` must be function.
2. That function must keep in memory the current value between calls.
3. According to the task, the function must become the number when used in `==`. Functions are objects, so the conversion happens as described in the chapter <info:object-toprimitive>, and we can provide our own method that returns the number.
1. Загалом, для того щоб все працювало *хоч як-небудь*, результат `sum` повинен бути функцією.
2. Ця функція повинна зберігати в пам’яті поточне значення між викликами.
3. Згідно з завданням, функція повинна стати числом, коли використовується в `==`. Функції -- це об’єкти, тому перетворення відбувається як описано в розділі <info:object-toprimitive>, і ми можемо надати власний метод, який повертає номер.

Now the code:
Тепер код:

```js demo run
function sum(a) {
Expand All @@ -28,28 +28,28 @@ alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15
```

Please note that the `sum` function actually works only once. It returns function `f`.
Зверніть увагу, що функція `sum` фактично працює лише раз. Вона повертає функцію `f`.

Then, on each subsequent call, `f` adds its parameter to the sum `currentSum`, and returns itself.
Потім, на кожному наступному виклику, `f` додає свій параметр до суми `currentSum`, і повертає себе.

**There is no recursion in the last line of `f`.**
**В останньому рядку `f` немає ніякої рекурсії.**

Here is what recursion looks like:
Ось як рекурсія виглядає:

```js
function f(b) {
currentSum += b;
return f(); // <-- recursive call
return f(); // <-- рекурсивний виклик
}
```

And in our case, we just return the function, without calling it:
А в нашому випадку ми просто повертаємо цю функцію, не викликаючи її:

```js
function f(b) {
currentSum += b;
return f; // <-- does not call itself, returns itself
return f; // <-- не викликає себе, повертає себе
}
```

This `f` will be used in the next call, again return itself, as many times as needed. Then, when used as a number or a string -- the `toString` returns the `currentSum`. We could also use `Symbol.toPrimitive` or `valueOf` here for the conversion.
Ця функція `f` буде використовуватися в наступному виклику і знову поверне себе стільки разів, скільки буде потрібно. Потім, при використанні функції як числа або рядка -- метод `toString` поверне `currentSum`. Тут ми також можемо використовувати `Symbol.toPrimitive` або `valueOf` для конверсії.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 2

---

# Sum with an arbitrary amount of brackets
# Сума з довільною кількістю дужок

Write function `sum` that would work like this:
Напишіть функцію `sum`, яка б працювала так:

```js
sum(1)(2) == 3; // 1 + 2
Expand All @@ -14,4 +14,4 @@ sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15
```

P.S. Hint: you may need to setup custom object to primitive conversion for your function.
P.S. Підказка: вам може знадобитися налаштувати кастомний об'єкт, щоб конвертувати примітиви для вашої функції.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
P.S. Підказка: вам може знадобитися налаштувати кастомний об'єкт, щоб конвертувати примітиви для вашої функції.
P.S. Підказка: вам може знадобитися налаштувати власний обєкт, щоб конвертувати примітиви для вашої функції.

Loading