Skip to content

Map and Set translation #148

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 13 commits into from
Jul 27, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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,13 +1,13 @@
describe("unique", function() {
it("removes non-unique elements", function() {
it("видалити не унікальні елементи", function() {
let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
];

assert.deepEqual(unique(strings), ["Hare", "Krishna", ":-O"]);
});

it("does not change the source array", function() {
it("не змінювати вихідний масив", function() {
let strings = ["Krishna", "Krishna", "Hare", "Hare"];
unique(strings);
assert.deepEqual(strings, ["Krishna", "Krishna", "Hare", "Hare"]);
Expand Down
14 changes: 7 additions & 7 deletions 1-js/05-data-types/07-map-set/01-array-unique-map/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Filter unique array members
# Фільтрувати унікальні елементи масиву

Let `arr` be an array.
Нехай `arr` - це масив.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Потрібно створити функцію `unique(arr)`, яка повинна повертати масив унікальних елементів `arr`.

For instance:
Наприклад:

```js
function unique(arr) {
/* your code */
/* Твій код */
}

let values = ["Hare", "Krishna", "Hare", "Krishna",
Expand All @@ -22,6 +22,6 @@ let values = ["Hare", "Krishna", "Hare", "Krishna",
alert( unique(values) ); // Hare, Krishna, :-O
```

P.S. Here strings are used, but can be values of any type.
P.S. В прикладі ми використали рядки, але можуть бути значення будь-якого типу.

P.P.S. Use `Set` to store unique values.
P.P.S. Використайте `Set` для формування множини унікальних значень.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ function intersection(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}

describe("aclean", function() {
describe("aclean", function () {

it("returns exactly 1 word from each anagram set", function() {
it("повертає тільки 1 слово для кожного набору анаграм", function () {
let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];

let result = aclean(arr);
Expand All @@ -16,7 +16,7 @@ describe("aclean", function() {

});

it("is case-insensitive", function() {
it("не враховує регістр", function () {
let arr = ["era", "EAR"];
assert.equal(aclean(arr).length, 1);
});
Expand Down
25 changes: 12 additions & 13 deletions 1-js/05-data-types/07-map-set/02-filter-anagrams/solution.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
To find all anagrams, let's split every word to letters and sort them. When letter-sorted, all anagrams are same.

For instance:
Щоб знайти всі анаграми, давайте розіб'ємо кожне слово на літери і відсортуємо їх, а потім об'єднаємо масив знову в рядок. Після цього всі анаграми будуть однакові.
Наприклад:

```
nap, pan -> anp
Expand All @@ -9,14 +8,14 @@ cheaters, hectares, teachers -> aceehrst
...
```

We'll use the letter-sorted variants as map keys to store only one value per each key:
Ми будемо використовувати відсортовані рядки як ключі в колекції Map, для того щоб зіставити кожному ключу тільки одне значення:

```js run
function aclean(arr) {
let map = new Map();

for (let word of arr) {
// split the word by letters, sort them and join back
// розділіть слово на літери, відсортуйте їх та знову з'єднайте
*!*
let sorted = word.toLowerCase().split('').sort().join(''); // (*)
*/!*
Expand All @@ -31,9 +30,9 @@ let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
alert( aclean(arr) );
```

Letter-sorting is done by the chain of calls in the line `(*)`.
Сортування літер здійснюється ланцюжком викликів одним рядком `(*)`.

For convenience let's split it into multiple lines:
Для зручності давайте розіб'ємо на декілька рядків:

```js
let sorted = word // PAN
Expand All @@ -43,21 +42,21 @@ let sorted = word // PAN
.join(''); // anp
```

Two different words `'PAN'` and `'nap'` receive the same letter-sorted form `'anp'`.
Два різних слова `'PAN'` і `'nap'` приймають ту ж саму форму після сортування букв - `'anp'`.

The next line put the word into the map:
Наступна лінія поміщає слово в об'єкт `Map`:

```js
map.set(sorted, word);
```

If we ever meet a word the same letter-sorted form again, then it would overwrite the previous value with the same key in the map. So we'll always have at maximum one word per letter-form.
Якщо ми коли-небудь ще зустрінемо слово в тій же відсортованої формі, тоді це слово перезапише значення з тим же ключем в об'єкті. Таким чином, декільком словами у нас буде завжди відповідати одна відсортована форма.

At the end `Array.from(map.values())` takes an iterable over map values (we don't need keys in the result) and returns an array of them.
Врешті-решт `Array.from(map.values())` приймає значення об'єкта-ітератора 'Map' (в цьому випадку нам не потрібні ключі) і повертає їх у вигляді масиву.

Here we could also use a plain object instead of the `Map`, because keys are strings.
Тут ми також можемо використовувати звичайний об'єкт замість `Map`, тому що ключі - це рядки.

That's how the solution can look:
Ось один з варіантів рішень задачі:

```js run demo
function aclean(arr) {
Expand Down
12 changes: 6 additions & 6 deletions 1-js/05-data-types/07-map-set/02-filter-anagrams/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ importance: 4

---

# Filter anagrams
# Відфільтруйте анаграми

[Anagrams](https://en.wikipedia.org/wiki/Anagram) are words that have the same number of same letters, but in different order.
[Анаграми](https://en.wikipedia.org/wiki/Anagram) -- це слова, у яких ті ж букви в тій же кількості, але вони розташовуються в іншому порядку.

For instance:
Наприклад:

```
nap - pan
ear - are - era
cheaters - hectares - teachers
```

Write a function `aclean(arr)` that returns an array cleaned from anagrams.
Напишіть функцію `aclean(arr)`, яка повертає масив без анаграм.

For instance:
Наприклад:

```js
let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];

alert( aclean(arr) ); // "nap,teachers,ear" or "PAN,cheaters,era"
```

From every anagram group should remain only one word, no matter which one.
З кожної групи анаграм має залишитися тільки одне слово, не має значення яке.

4 changes: 2 additions & 2 deletions 1-js/05-data-types/07-map-set/03-iterable-keys/solution.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

That's because `map.keys()` returns an iterable, but not an array.
Ми отримали помилку тому, що `map.keys()` повертає об'єкт-ітератор, а не масив.

We can convert it into an array using `Array.from`:
Ми можемо конвертувати його використовуючи `Array.from`:


```js run
Expand Down
10 changes: 5 additions & 5 deletions 1-js/05-data-types/07-map-set/03-iterable-keys/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Iterable keys
# Перебираємо ключі

We'd like to get an array of `map.keys()` in a variable and then apply array-specific methods to it, e.g. `.push`.
Ми хотіли б отримати масив ключів `map.keys()` в змінну і далі працювати з ними, наприклад, застосувати метод `.push`.

But that doesn't work:
Але так не спрацює:

```js run
let map = new Map();
Expand All @@ -16,9 +16,9 @@ map.set("name", "John");
let keys = map.keys();

*!*
// Error: keys.push is not a function
// Помилка: keys.push -- це не функція
keys.push("more");
*/!*
```

Why? How can we fix the code to make `keys.push` work?
Чому? Що потрібно виправити в коді, щоб `keys.push` працював?
Loading