-
Notifications
You must be signed in to change notification settings - Fork 183
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
tarasyyyk
merged 17 commits into
javascript-tutorial:master
from
MykolaSopiha:weakmap-weakset
Aug 3, 2021
Merged
WeakMap and WeakSet #162
Changes from 5 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
cb04679
weakmap-weakset
MykolaSopiha d05e96c
weakmap-weakset
MykolaSopiha de875f0
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solut…
tarasyyyk 53ba2d7
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solut…
tarasyyyk 3453940
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md
tarasyyyk dba6c68
Update 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md
tarasyyyk 559276e
Update 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/…
tarasyyyk 2905374
Update 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/…
tarasyyyk eb1c521
weakmap-weakset
MykolaSopiha 11577f6
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha fb97f49
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha 2d442b9
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha b57764a
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha 419af44
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha 8dac342
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha f5eb970
Update 1-js/05-data-types/08-weakmap-weakset/article.md
MykolaSopiha 44c5f94
Merge branch 'weakmap-weakset' of github.com:MykolaSopiha/uk.javascri…
MykolaSopiha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
36 changes: 18 additions & 18 deletions
36
1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solution.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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` краще з архітектурної точки зору. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 5 additions & 5 deletions
10
1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/solution.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ми розглянемо пізніше | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.