Skip to content

Update 1-JS/05/05(Array-Methods) & 1-JS/05/08(Keys-Values-Entries) #1

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 2 commits into from
Apr 18, 2019
Merged
Show file tree
Hide file tree
Changes from all 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,10 +1,10 @@
function camelize(str) {
return str
.split('-') // splits 'my-long-word' into array ['my', 'long', 'word']
.map(
// capitalizes first letters of all array items except the first one
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
.split('-') // divise 'my-long-word' en tableau ['my', 'long', 'word']
.map(
// capitalise les premières lettres de tous les éléments du tableau sauf le premier
// convertit ['my', 'long', 'word'] en ['my', 'Long', 'Word']
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord'
.join(''); // rejoint ['my', 'Long', 'Word'] en -> myLongWord
}
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/1-camelcase/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 5

---

# Translate border-left-width to borderLeftWidth
# Traduit border-left-width en borderLeftWidth

Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
Ecrivez la fonction `camelize(str)` qui change les mots séparés par des tirets comme "my-short-string" en camel-cased "myShortString".

That is: removes all dashes, each word after dash becomes uppercased.
Donc: supprime tous les tirets et met en majuscule la première lettre de chaque mot à partir du deuxième mot.

Examples:
Exemples:

```js
camelize("background-color") == 'backgroundColor';
camelize("list-style-image") == 'listStyleImage';
camelize("-webkit-transition") == 'WebkitTransition';
```

P.S. Hint: use `split` to split the string into an array, transform it and `join` back.
P.S. Astuce: utilisez `split` pour scinder la chaîne dans un tableau, transformer la et ensuite `join`.
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/10-average-age/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 4

---

# Get average age
# Obtenir l'âge moyen

Write the function `getAverageAge(users)` that gets an array of objects with property `age` and gets the average.
Ecrivez la fonction `getAverageAge(users)` qui obtient un tableau d'objets avec la propriété `age` et qui ensuite obtient la moyenne.

The formula for the average is `(age1 + age2 + ... + ageN) / N`.
La formule pour la moyenne est `(age1 + age2 + ... + ageN) / N`.

For instance:
Par exemple:

```js no-beautify
let john = { name: "John", age: 25 };
Expand Down
24 changes: 12 additions & 12 deletions 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Let's walk the array items:
- For each item we'll check if the resulting array already has that item.
- If it is so, then ignore, otherwise add to results.
Parcourons les éléments du tableau:
- Pour chaque élément, nous vérifierons si le tableau résultant contient déjà cet élément.
- S'il en est ainsi, alors ignorez-le, sinon ajoutez aux résultats.

```js run demo
```js run
function unique(arr) {
let result = [];

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

The code works, but there's a potential performance problem in it.
Le code fonctionne, mais il comporte un problème de performances potentiel.

The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
La méthode `result.includes(str)` parcourt en interne le tableau `result` et compare chaque élément à `str` pour trouver la correspondance.

So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons.
Donc, s'il y a `100` éléments dans` result` et que personne ne correspond à `str`, alors il parcourra tout le `result` et fera exactement les `100` comparaisons. Et si `result` est grand, exemple `10000`, alors il y aura des `10000` comparaisons .

That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
Ce n'est pas un problème en soi, parce que les moteurs JavaScript sont très rapides, alors parcourir un tableau de `10000` éléments est une question de microsecondes.

But we do such test for each element of `arr`, in the `for` loop.
Mais nous faisons ce test pour chaque élément de `arr`, dans la boucle` for`.

So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
Donc, si `arr.length` vaut `10000`, nous aurons quelque chose comme `10000*10000` = 100 millions de comparaisons. C'est beaucoup.

So the solution is only good for small arrays.
La solution n’est donc valable que pour les petits tableaux.

Further in the chapter <info:map-set-weakmap-weakset> we'll see how to optimize it.
Plus loin dans le chapitre <info:map-set-weakmap-weakset>, nous verrons comment l'optimiser.
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/11-array-unique/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 4

---

# Filter unique array members
# Filtrer les membres uniques du tableau

Let `arr` be an array.
`arr` est un tableau.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Créez une fonction `unique(arr)` qui devrait renvoyer un tableau avec des éléments uniques de `arr`.

For instance:
Par exemple:

```js
function unique(arr) {
/* your code */
/* votre code */
}

let strings = ["Hare", "Krishna", "Hare", "Krishna",
Expand Down
28 changes: 14 additions & 14 deletions 1-js/05-data-types/05-array-methods/2-filter-range/solution.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
```js run demo
function filterRange(arr, a, b) {
// added brackets around the expression for better readability
return arr.filter(item => (a <= item && item <= b));
}
let arr = [5, 3, 8, 1];
let filtered = filterRange(arr, 1, 4);
alert( filtered ); // 3,1 (matching values)
alert( arr ); // 5,3,8,1 (not modified)
```
```js run demo
function filterRange(arr, a, b) {
// ajout de crochets autour de l'expression pour une meilleure lisibilité
return arr.filter(item => (a <= item && item <= b));
}

let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (valeur correspondate)

alert( arr ); // 5,3,8,1 (non modifié)
```
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/2-filter-range/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ importance: 4

# Filter range

Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them.
Ecrivez une fonction `filterRange(arr, a, b)` qui obtient un tableau `arr`, recherche les éléments compris entre `a` et `b` et retourne un tableau.

The function should not modify the array. It should return the new array.
La fonction ne doit pas modifier le tableau. Elle doit juste retourner le nouveau tableau.

For instance:
Par exemple:

```js
let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (valeurs correspondantes)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (non modifié)
```

Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ function filterRangeInPlace(arr, a, b) {

for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
// enleve si en dehors de l'intervalle
if (val < a || val > b) {
arr.splice(i, 1);
i--;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
```js run demo
function filterRangeInPlace(arr, a, b) {
for (let i = 0; i < arr.length; i++) {
let val = arr[i];
// remove if outside of the interval
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
}
}
let arr = [5, 3, 8, 1];
filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
alert( arr ); // [3, 1]
```
```js run demo
function filterRangeInPlace(arr, a, b) {

for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// enleve si en dehors de l'intervalle
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
}

}

let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); // supprime les nombres sauf de 1 à 4

alert( arr ); // [3, 1]
```
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ importance: 4

# Filter range "in place"

Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b`. The test is: `a ≤ arr[i] ≤ b`.
Ecrivez une fonction `filterRangeInPlace(arr, a, b)` qui obtient un tableau `arr` et en supprime toutes les valeurs, sauf celles comprises entre `a` et `b`. Le test est: `a ≤ arr[i] ≤ b`.

The function should only modify the array. It should not return anything.
La fonction doit juste modifier que le tableau. Elle ne doit rien retourner.

For instance:
Par exemple:
```js
let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); // supprime les nombres qui ne sont pas entre 1 et 4

alert( arr ); // [3, 1]
```
4 changes: 2 additions & 2 deletions 1-js/05-data-types/05-array-methods/4-sort-back/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 4

---

# Sort in the reverse order
# Trier dans l'ordre inverse

```js
let arr = [5, 2, 1, -10, 8];

// ... your code to sort it in the reverse order
// ... votre code pour le trier dans l'ordre inverse

alert( arr ); // 8, 5, 2, 1, -10
```
Expand Down
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Copy and sort array
# Copier et trier le tableau

We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified.
Nous avons un tableau de chaînes `arr`. Nous aimerions en avoir une copie triée, mais sans modifier `arr`.

Create a function `copySorted(arr)` that returns such a copy.
Créez une fonction `copySorted(arr)` qui renvoie une copie triée.

```js
let arr = ["HTML", "JavaScript", "CSS"];

let sorted = copySorted(arr);

alert( sorted ); // CSS, HTML, JavaScript
alert( arr ); // HTML, JavaScript, CSS (no changes)
alert( arr ); // HTML, JavaScript, CSS (aucune modification)
```
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/6-array-get-names/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ importance: 5

---

# Map to names
# Map en noms

You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names.
Vous avez un tableau d'objets `user`, chacun ayant` user.name`. Écrivez le code qui le convertit en un tableau de noms.

For instance:
Par exemple:

```js no-beautify
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };

let users = [ john, pete, mary ];
let users = [ john, petemary ];

let names = /* ... your code */
let names = /* ... votre code */

alert( names ); // John, Pete, Mary
```
Expand Down
12 changes: 6 additions & 6 deletions 1-js/05-data-types/05-array-methods/7-map-objects/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Map to objects
# Map en objets

You have an array of `user` objects, each one has `name`, `surname` and `id`.
Vous avez un tableau d'objets `user`, chacun ayant` name`, `surname` et` id`.

Write the code to create another array from it, of objects with `id` and `fullName`, where `fullName` is generated from `name` and `surname`.
Ecrivez le code pour créer un autre tableau à partir de celui-ci, avec les objets `id` et `fullName`, `fullName` est généré à partir de `name` et `surname`.

For instance:
Par exemple:

```js no-beautify
let john = { name: "John", surname: "Smith", id: 1 };
Expand All @@ -18,7 +18,7 @@ let mary = { name: "Mary", surname: "Key", id: 3 };
let users = [ john, pete, mary ];

*!*
let usersMapped = /* ... your code ... */
let usersMapped = /* ... votre code ... */
*/!*

/*
Expand All @@ -33,4 +33,4 @@ alert( usersMapped[0].id ) // 1
alert( usersMapped[0].fullName ) // John Smith
```

So, actually you need to map one array of objects to another. Try using `=>` here. There's a small catch.
Donc, en réalité, vous devez mapper un tableau d'objets sur un autre. Essayez d'utiliser `=>` ici. Il y a une petite prise.
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/8-sort-objects/solution.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
```js run no-beautify
function sortByAge(arr) {
arr.sort((a, b) => a.age > b.age ? 1 : -1);
function sortByName(arr) {
arr.sort((a, b) => a.name > b.name);
}

let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };

let arr = [ pete, john, mary ];
let arr = [ john, pete, mary ];

sortByAge(arr);
sortByName(arr);

// now sorted is: [john, mary, pete]
// maitenant trié il est: [john, mary, pete]
alert(arr[0].name); // John
alert(arr[1].name); // Mary
alert(arr[2].name); // Pete
Expand Down
12 changes: 6 additions & 6 deletions 1-js/05-data-types/05-array-methods/8-sort-objects/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ importance: 5

---

# Sort users by age
# Trier les objets

Write the function `sortByAge(users)` that gets an array of objects with the `age` property and sorts them by `age`.
Ecrivez la fonction `sortByName(users)` qui obtient un tableau d'objets avec la propriété `name` et le trie.

For instance:
Par exemple:

```js no-beautify
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };

let arr = [ pete, john, mary ];
let arr = [ john, pete, mary ];

sortByAge(arr);
sortByName(arr);

// now: [john, mary, pete]
// maintenant: [john, mary, pete]
alert(arr[0].name); // John
alert(arr[1].name); // Mary
alert(arr[2].name); // Pete
Expand Down
Loading