Skip to content

Map and Set #405

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 14 commits into from
Dec 20, 2023
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
describe("unique", function() {
it("removes non-unique elements", function() {
it("remove elementos não únicos", 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("não altera o array de origem", function () {
let strings = ["Krishna", "Krishna", "Hare", "Hare"];
unique(strings);
assert.deepEqual(strings, ["Krishna", "Krishna", "Hare", "Hare"]);
Expand Down
12 changes: 6 additions & 6 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,13 +2,13 @@ importance: 5

---

# Filter unique array members
# Filtrar elementos únicos de um array

Let `arr` be an array.
Seja `arr` um array.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Crie uma função `unique(arr)` que deve retornar um array com itens únicos de `arr`.

For instance:
Por exemplo:

```js
function unique(arr) {
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.
Observação: Aqui estão sendo usadas strings, mas os valores podem ser de qualquer tipo.

P.P.S. Use `Set` to store unique values.
Observação adicional: Use `Set` para armazenar valores únicos.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ function intersection(arr1, arr2) {
}

describe("aclean", function() {

it("returns exactly 1 word from each anagram set", function() {
it("retorna exatamente 1 palavra de cada conjunto de anagramas", function () {
let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];

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

});

it("is case-insensitive", function() {
it("é insensível a maiúsculas e minúsculas", function () {
let arr = ["era", "EAR"];
assert.equal(aclean(arr).length, 1);
});

});
});
24 changes: 12 additions & 12 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,6 @@
To find all anagrams, let's split every word to letters and sort them. When letter-sorted, all anagrams are same.
Para encontrar todos os anagramas, vamos dividir cada palavra em letras e ordená-las. Quando ordenadas por letras, todos os anagramas são iguais.

For instance:
Por exemplo:

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

We'll use the letter-sorted variants as map keys to store only one value per each key:
Vamos usar as variantes ordenadas por letras como chaves de mapa para armazenar apenas um valor para cada chave:

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

for (let word of arr) {
// split the word by letters, sort them and join back
// Divida a palavra em letras, ordene-as e junte novamente.
*!*
let sorted = word.toLowerCase().split('').sort().join(''); // (*)
*/!*
Expand All @@ -31,9 +31,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 `(*)`.
A ordenação por letras é feita pela cadeia de chamadas na linha `(*)`.

For convenience let's split it into multiple lines:
Para maior clareza, vamos dividi-la em várias linhas:

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

Two different words `'PAN'` and `'nap'` receive the same letter-sorted form `'anp'`.
Duas palavras diferentes, `'PAN'` e `'nap'`, recebem a mesma forma ordenada por letras, `'anp'`.

The next line put the word into the map:
A próxima linha coloca a palavra no mapa:

```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.
Se encontrarmos novamente uma palavra com a mesma forma ordenada por letras, ela irá sobrescrever o valor anterior com a mesma chave no mapa. Portanto, sempre teremos no máximo uma palavra por forma de letras.

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.
No final, `Array.from(map.values())` cria um iterável sobre os valores do mapa (não precisamos das chaves no resultado) e retorna um array com eles.

Here we could also use a plain object instead of the `Map`, because keys are strings.
Aqui também poderíamos usar um objeto simples em vez do `Map`, porque as chaves são strings.

That's how the solution can look:
É assim que a solução pode ser implementada:

```js run demo
function aclean(arr) {
Expand Down
15 changes: 7 additions & 8 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,26 @@ importance: 4

---

# Filter anagrams
# Filtrar anagramas

[Anagrams](https://en.wikipedia.org/wiki/Anagram) are words that have the same number of same letters, but in different order.
[Anagramas](https://en.wikipedia.org/wiki/Anagram) são palavras que têm o mesmo número das mesmas letras, mas em ordem diferente.

For instance:
Por exemplo:

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

Write a function `aclean(arr)` that returns an array cleaned from anagrams.
Escreva uma função `aclean(arr)` que retorne um array limpo de anagramas.

For instance:
Por exemplo:

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

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

From every anagram group should remain only one word, no matter which one.

De cada grupo de anagramas, deve permanecer apenas uma palavra, não importa qual.
5 changes: 2 additions & 3 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,8 +1,7 @@

That's because `map.keys()` returns an iterable, but not an array.

We can convert it into an array using `Array.from`:
Isso ocorre porque `map.keys()` retorna um objeto iterável, mas não um array.

Podemos convertê-lo em um array usando `Array.from`:

```js run
let map = new Map();
Expand Down
6 changes: 3 additions & 3 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 @@ -4,9 +4,9 @@ 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`.
Gostaríamos de obter um array de `map.keys()` em uma variável e, em seguida, aplicar métodos específicos de array a ele, como `.push`.

But that doesn't work:
Mas isso não funciona:

```js run
let map = new Map();
Expand All @@ -21,4 +21,4 @@ keys.push("more");
*/!*
```

Why? How can we fix the code to make `keys.push` work?
Por quê? Como podemos corrigir o código para fazer com que `keys.push` funcione?
Loading