Skip to content

WeakMap and WeakSet #162

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 17 commits into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
cb04679
weakmap-weakset
MykolaSopiha Jul 28, 2021
d05e96c
weakmap-weakset
MykolaSopiha Jul 29, 2021
de875f0
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solut…
tarasyyyk Jul 29, 2021
53ba2d7
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solut…
tarasyyyk Jul 29, 2021
3453940
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md
tarasyyyk Jul 29, 2021
dba6c68
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md
tarasyyyk Jul 29, 2021
559276e
Update 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/…
tarasyyyk Jul 29, 2021
2905374
Update 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/…
tarasyyyk Jul 29, 2021
eb1c521
weakmap-weakset
MykolaSopiha Jul 29, 2021
11577f6
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
fb97f49
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
2d442b9
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
b57764a
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
419af44
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
8dac342
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
f5eb970
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha Jul 29, 2021
44c5f94
Merge branch 'weakmap-weakset' of github.com:MykolaSopiha/uk.javascri…
MykolaSopiha Jul 29, 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,43 +1,43 @@
Let's store read messages in `WeakSet`:
Збережемо прочитані повідомлення у `WeakSet`:

```js run
let messages = [
{text: "Hello", from: "John"},
{text: "How goes?", from: "John"},
{text: "See you soon", from: "Alice"}
{text: "Привіт", from: "Іван"},
{text: "Як справи?", from: "Іван"},
{text: "До зустрічі", from: "Аліса"}
];

let readMessages = new WeakSet();

// two messages have been read
// були прочитані два повідомлення
readMessages.add(messages[0]);
readMessages.add(messages[1]);
// readMessages has 2 elements
// readMessages має 2 елементи

// ...let's read the first message again!
// ...давайте знову прочитаємо перше повідомлення!
readMessages.add(messages[0]);
// readMessages still has 2 unique elements
// readMessages все ще має 2 унікальних елементів

// answer: was the message[0] read?
alert("Read message 0: " + readMessages.has(messages[0])); // true
// відповідь: чи було messages[0] прочитано?
alert("Прочитано повідомлення 0: " + readMessages.has(messages[0])); // true

messages.shift();
// now readMessages has 1 element (technically memory may be cleaned later)
// зараз readMessages має 1 елемент (з технічної точки зору пам’ять може бути очищена пізніше)
```

The `WeakSet` allows to store a set of messages and easily check for the existence of a message in it.
`WeakSet` дозволяє зберігати набір повідомлень і легко перевірити наявність повідомлення в наборі.

It cleans up itself automatically. The tradeoff is that we can't iterate over it, can't get "all read messages" from it directly. But we can do it by iterating over all messages and filtering those that are in the set.
Він автоматично очищає себе. Компроміс полягає в тому, що ми не можемо ітеруватися через нього, не можемо отримати "всі прочитані повідомлення" від нього безпосередньо. Але ми можемо це зробити, ітеруючись через всі повідомлення та відфільтрувавши тих, що знаходяться у наборі.

Another, different solution could be to add a property like `message.isRead=true` to a message after it's read. As messages objects are managed by another code, that's generally discouraged, but we can use a symbolic property to avoid conflicts.
Інше рішення може полягати у додаванні властивості `message.isRead=true` до повідомлення після його прочитання. Оскільки об’єкти повідомлень керуються іншим кодом, це, як правило, збентежує, але ми можемо використовувати символьну властивість, щоб уникнути конфліктів.

Like this:
Ось так:
```js
// the symbolic property is only known to our code
// символьна властивість відома лише в нашому коді
let isRead = Symbol("isRead");
messages[0][isRead] = true;
```

Now third-party code probably won't see our extra property.
Тепер сторонній код, ймовірно, не побачить нашу додаткову властивість.

Although symbols allow to lower the probability of problems, using `WeakSet` is better from the architectural point of view.
Незважаючи на те, що символи дозволяють знизити ймовірність проблем, використання `WeakSet` краще з архітектурної точки зору.
18 changes: 9 additions & 9 deletions 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ importance: 5

---

# Store "unread" flags
# Зберігати мітки "непрочитане"

There's an array of messages:
Є масив повідомлень:

```js
let messages = [
{text: "Hello", from: "John"},
{text: "How goes?", from: "John"},
{text: "See you soon", from: "Alice"}
{text: "Привіт", from: "Іван"},
{text: "Як справи?", from: "Іван"},
{text: "До зустрічі", from: "Аліса"}
];
```

Your code can access it, but the messages are managed by someone else's code. New messages are added, old ones are removed regularly by that code, and you don't know the exact moments when it happens.
Ваш код може отримати доступ до нього, але повідомлення керуються чужим кодом. Нові повідомлення додаються, старі видаляються регулярно цим кодом, і ви не знаєте точних моментів, коли це станеться.

Now, which data structure could you use to store information about whether the message "has been read"? The structure must be well-suited to give the answer "was it read?" for the given message object.
Тепер, яку структуру даних ви могли б використати для зберігання інформації про те, чи було повідомлення прочитаним? Структура повинна добре підходити, щоб дати відповідь на питання "чи він прочитаний?" для об’єкта даного повідомлення.

P.S. When a message is removed from `messages`, it should disappear from your structure as well.
P.S. Коли повідомлення видаляється з `messages`, воно також повинне зникнути з вашої структури.

P.P.S. We shouldn't modify message objects, add our properties to them. As they are managed by someone else's code, that may lead to bad consequences.
P.P.S. Ми не повинні змінювати об’єкти повідомлення, додаючи до них наші властивості. Оскільки вони керуються іншим кодом, це може призвести до поганих наслідків.
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@

To store a date, we can use `WeakMap`:
Щоб зберегти дату, ми можемо використовувати `WeakMap`:

```js
let messages = [
{text: "Hello", from: "John"},
{text: "How goes?", from: "John"},
{text: "See you soon", from: "Alice"}
{text: "Привіт", from: "Іван"},
{text: "Як справи?", from: "Іван"},
{text: "До зустрічі", from: "Аліса"}
];

let readMap = new WeakMap();

readMap.set(messages[0], new Date(2017, 1, 1));
// Date object we'll study later
// об’єкт Date ми розглянемо пізніше
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ importance: 5

---

# Store read dates
# Зберігати дати читання

There's an array of messages as in the [previous task](info:task/recipients-read). The situation is similar.
Є масив повідомлень, як у [попередньому завдані](info:task/recipients-read). Ситуація схожа.

```js
let messages = [
{text: "Hello", from: "John"},
{text: "How goes?", from: "John"},
{text: "See you soon", from: "Alice"}
{text: "Привіт", from: "Іван"},
{text: "Як справи?", from: "Іван"},
{text: "До зустрічі", from: "Аліса"}
];
```

The question now is: which data structure you'd suggest to store the information: "when the message was read?".
Зараз питання наступне: яку структуру даних ви б запропонували для того, щоб зберегти інформацію: "Коли повідомлення було прочитано?".

In the previous task we only needed to store the "yes/no" fact. Now we need to store the date, and it should only remain in memory until the message is garbage collected.
У попередньому завданні нам потрібно лише зберігати інформацію "так/ні". Тепер нам потрібно зберігати дату, і це повинно залишитися в пам’яті лише доки повідомлення не буде видалено.

P.S. Dates can be stored as objects of built-in `Date` class, that we'll cover later.
P.S. Дати можуть зберігатися як об’єкти вбудованого класу `Data`, що ми розглянемо пізніше.
Loading