Skip to content
Merged
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
@@ -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
@@ -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 };
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 = [];

@@ -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
@@ -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",
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
@@ -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
@@ -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--;
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
@@ -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
@@ -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
```
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
@@ -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
@@ -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
```
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
@@ -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 };
@@ -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 ... */
*/!*

/*
@@ -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
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
@@ -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
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/9-shuffle/task.md
Original file line number Diff line number Diff line change
@@ -2,11 +2,11 @@ importance: 3

---

# Shuffle an array
# Mélanger un tableau

Write the function `shuffle(array)` that shuffles (randomly reorders) elements of the array.
Ecrivez la fonction `shuffle(array)` qui mélange les éléments (de manière aléatoire) du tableau.

Multiple runs of `shuffle` may lead to different orders of elements. For instance:
Les exécutions multiples de `shuffle` peuvent conduire à différents ordres d'éléments. Par exemple:

```js
let arr = [1, 2, 3];
@@ -22,4 +22,4 @@ shuffle(arr);
// ...
```

All element orders should have an equal probability. For instance, `[1,2,3]` can be reordered as `[1,2,3]` or `[1,3,2]` or `[3,1,2]` etc, with equal probability of each case.
Tous les ordres d'éléments doivent avoir une probabilité égale. Par exemple, `[1,2,3]` peut être réorganisé comme `[1,2,3]` ou `[1,3,2]` ou `[3,1,2]` etc., avec une probabilité égale de chaque cas.
448 changes: 224 additions & 224 deletions 1-js/05-data-types/05-array-methods/article.md
100644 → 100755

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -2,15 +2,15 @@ importance: 5

---

# Sum the properties
# Additionner les propriétés

There is a `salaries` object with arbitrary number of salaries.
Il existe un objet `salaries` object avec un nombre arbitraire de salaires.

Write the function `sumSalaries(salaries)` that returns the sum of all salaries using `Object.values` and the `for..of` loop.
Ecrivez la fonction `sumSalaries(salaries)` qui retourne la somme des salaires en utilisant `Object.values` et la boucle `for..of`.

If `salaries` is empty, then the result must be `0`.
Si `salaries` est vide, le résultat doit être `0`.

For instance:
Par exemple:

```js
let salaries = {
Original file line number Diff line number Diff line change
@@ -2,9 +2,9 @@ importance: 5

---

# Count properties
# Compter les propriétés

Write a function `count(obj)` that returns the number of properties in the object:
Ecrivez la fonction `count(obj)` qui retourne le nombre de propriétés qu'il y a dans l'objet:

```js
let user = {
@@ -15,7 +15,7 @@ let user = {
alert( count(user) ); // 2
```

Try to make the code as short as possible.
Essayer d'écrire le code le plus petit possible.

P.S. Ignore symbolic properties, count only "regular" ones.
P.S: Ignorez les propriétés symboliques, ne comptez que les propriétés "normales".

49 changes: 24 additions & 25 deletions 1-js/05-data-types/08-keys-values-entries/article.md
Original file line number Diff line number Diff line change
@@ -1,42 +1,41 @@

# Object.keys, values, entries

Let's step away from the individual data structures and talk about the iterations over them.
Éloignons-nous des structures de données individuelles et parlons des itérations les concernant.

In the previous chapter we saw methods `map.keys()`, `map.values()`, `map.entries()`.
Dans le chapitre précédent, nous avons vu les méthodes `map.keys()`, `map.values()`, `map.entries()`.

These methods are generic, there is a common agreement to use them for data structures. If we ever create a data structure of our own, we should implement them too.
Ces méthodes sont génériques, il existe un accord commun pour les utiliser dans les structures de données. Si jamais nous créons notre propre structure de données, nous devrions aussi les implémenter.

They are supported for:
Ils sont pris en charge par:

- `Map`
- `Set`
- `Array` (except `arr.values()`)
- `Array` (sauf `arr.values()`)

Plain objects also support similar methods, but the syntax is a bit different.
Les objets simples prennent également en charge des méthodes similaires, mais la syntaxe est un peu différente.

## Object.keys, values, entries

For plain objects, the following methods are available:
Pour les objets simples, les méthodes suivantes sont disponibles:

- [Object.keys(obj)](mdn:js/Object/keys) -- returns an array of keys.
- [Object.values(obj)](mdn:js/Object/values) -- returns an array of values.
- [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of `[key, value]` pairs.
- [Object.keys(obj)](mdn:js/Object/keys) -- retourne un tableau de clés.
- [Object.values(obj)](mdn:js/Object/values) -- retourne un tableau de valeurs.
- [Object.entries(obj)](mdn:js/Object/entries) -- retourne un tableau de paires `[clé, valeur]`.

...But please note the distinctions (compared to map for example):
...Mais s'il vous plaît noter les différences (par rapport à map par exemple):

| | Map | Object |
|-------------|------------------|--------------|
| Call syntax | `map.keys()` | `Object.keys(obj)`, but not `obj.keys()` |
| Returns | iterable | "real" Array |
| Syntaxe d'appel | `map.keys()` | `Object.keys(obj)`, mais pas `obj.keys()` |
| Retours | iterable | "vrai" Array |

The first difference is that we have to call `Object.keys(obj)`, and not `obj.keys()`.
La première différence est que nous devons appeler `Object.keys(obj)` et non `obj.keys()`.

Why so? The main reason is flexibility. Remember, objects are a base of all complex structures in JavaScript. So we may have an object of our own like `order` that implements its own `order.values()` method. And we still can call `Object.values(order)` on it.
Pourquoi ça? La principale raison est la flexibilité. N'oubliez pas que les objets sont une base de toutes les structures complexes en JavaScript. Ainsi, nous pouvons avoir un objet de notre propre `order` qui implémente sa propre méthode `order.values()`. Et nous pouvons toujours appeler `Object.values(order)` dessus.

The second difference is that `Object.*` methods return "real" array objects, not just an iterable. That's mainly for historical reasons.
La seconde différence réside dans le fait que les méthodes `Object.*` retourne de "réels" objets de tableau, et pas seulement des objets itératifs. C'est principalement pour des raisons historiques.

For instance:
Par exemple:

```js
let user = {
@@ -45,26 +44,26 @@ let user = {
};
```

- `Object.keys(user) = ["name", "age"]`
- `Object.keys(user) = [name, age]`
- `Object.values(user) = ["John", 30]`
- `Object.entries(user) = [ ["name","John"], ["age",30] ]`

Here's an example of using `Object.values` to loop over property values:
Voici un exemple d'utilisation d'`Object.values` pour boucler les valeurs de propriété:

```js run
let user = {
name: "John",
age: 30
};

// loop over values
// boucle sur les valeurs
for (let value of Object.values(user)) {
alert(value); // John, then 30
alert(value); // John, ensuite 30
}
```

## Object.keys/values/entries ignore symbolic properties
## Object.keys/values/entries ignorer les propriétés symboliques

Just like a `for..in` loop, these methods ignore properties that use `Symbol(...)` as keys.
Tout comme une boucle `for..in`, ces méthodes ignorent les propriétés qui utilisent `Symbol(...)` comme clés.

Usually that's convenient. But if we want symbolic keys too, then there's a separate method [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols) that returns an array of only symbolic keys. Also, the method [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) returns *all* keys.
D'habitude c'est pratique. Mais si nous voulons aussi des clés symboliques, il existe une méthode distincte [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols) qui retourne un tableau composé uniquement de clés symboliques. De plus, la méthde [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) renvoie *toutes* les clés.