Skip to content

Commit fcf928d

Browse files
committed
- Minor style modifications.
- Subtle refactoring of functions.
1 parent e996b28 commit fcf928d

8 files changed

Lines changed: 341 additions & 414 deletions

File tree

data.js

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,8 @@ export function createAll() {
7979
return companies;
8080
}
8181

82-
function clone(value) {
83-
return Object.keys(value).map((key) => {
84-
value[key].users = value[key].users.map((user) => ({...user}));
85-
value[key] = {...value[key]};
86-
return value[key];
87-
});
88-
}
89-
9082
export function cleanConsole(index, value) {
91-
const result = clone(value);
9283
console.log(`---- EXAMPLE ${index} --- values before your modifications :`,
93-
result);
84+
JSON.parse(JSON.stringify(value)),
85+
);
9486
}

example-1.js

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,36 @@
11
import {createAll, cleanConsole} from './data';
22
const companies = createAll();
33

4+
// -----------------------------------------------------------------------------
5+
// INSTRUCTIONS IN ENGLISH
6+
7+
// Create a function taking the variable "companies" as a parameter and replacing
8+
// all values "undefined" in "users" by an empty string.
9+
// The name of each "company" must have a capital letter at the beginning as well as
10+
// the last name and first name of each "user".
11+
// The "companies" must be sorted by their number of "user" (decreasing order)
12+
// and the "users" of each "company" must be listed in alphabetical order.
13+
14+
// -----------------------------------------------------------------------------
15+
// INSTRUCCIONES EN ESPAÑOL
16+
17+
// Crear una función tomando la variable "companies" como parámetro y reemplazando
18+
// todos los valores "undefined" en "usuarios" por un string vacío.
19+
// El nombre de cada "company" debe tener una letra mayúscula al principio, así como
20+
// el apellido y el nombre de cada "user".
21+
// Las "companies" deben ordenarse por su total de "user" (orden decreciente)
22+
// y los "users" de cada "company" deben aparecer en orden alfabético.
23+
24+
// -----------------------------------------------------------------------------
25+
// INSTRUCTIONS EN FRANÇAIS
26+
27+
// Créer une fonction prenant en paramètre la variable "companies" et remplaçant
28+
// toutes les valeurs "undefined" dans les "users" par un string vide.
29+
// Le nom de chaque "company" doit avoir une majuscule au début ainsi que
30+
// le nom et le prénom de chaque "user".
31+
// Les "companies" doivent être triées par leur nombre de "user" (ordre décroissant)
32+
// et les "users" de chaque "company" doivent être classés par ordre alphabétique.
33+
434
/**
535
* Capitalize a string
636
* from https://flaviocopes.com/how-to-uppercase-first-letter-javascript/
@@ -51,33 +81,3 @@ export default function f1(entity) {
5181

5282
cleanConsole(1, companies);
5383
console.log('---- EXAMPLE 1 --- ', f1(companies));
54-
55-
// -----------------------------------------------------------------------------
56-
// INSTRUCTIONS IN ENGLISH
57-
58-
// Create a function taking the variable "companies" as a parameter and replacing
59-
// all values "undefined" in "users" by an empty string.
60-
// The name of each "company" must have a capital letter at the beginning as well as
61-
// the last name and first name of each "user".
62-
// The "companies" must be sorted by their number of "user" (decreasing order)
63-
// and the "users" of each "company" must be listed in alphabetical order.
64-
65-
// -----------------------------------------------------------------------------
66-
// INSTRUCCIONES EN ESPAÑOL
67-
68-
// Crear una función tomando la variable "companies" como parámetro y reemplazando
69-
// todos los valores "undefined" en "usuarios" por un string vacío.
70-
// El nombre de cada "company" debe tener una letra mayúscula al principio, así como
71-
// el apellido y el nombre de cada "user".
72-
// Las "companies" deben ordenarse por su total de "user" (orden decreciente)
73-
// y los "users" de cada "company" deben aparecer en orden alfabético.
74-
75-
// -----------------------------------------------------------------------------
76-
// INSTRUCTIONS EN FRANÇAIS
77-
78-
// Créer une fonction prenant en paramètre la variable "companies" et remplaçant
79-
// toutes les valeurs "undefined" dans les "users" par un string vide.
80-
// Le nom de chaque "company" doit avoir une majuscule au début ainsi que
81-
// le nom et le prénom de chaque "user".
82-
// Les "companies" doivent être triées par leur nombre de "user" (ordre décroissant)
83-
// et les "users" de chaque "company" doivent être classés par ordre alphabétique.

example-2.js

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,6 @@
11
import {cleanConsole, createAll} from './data';
22
const companies = createAll();
33

4-
export default function f2(companies, hasCar) {
5-
return companies.map(
6-
(company) => {
7-
const users = company.users.filter(
8-
(u) => (u.car === hasCar),
9-
);
10-
11-
return {
12-
...company,
13-
users,
14-
usersLength: users.length,
15-
};
16-
});
17-
};
18-
19-
cleanConsole(2, companies);
20-
console.log('---- EXAMPLE 2 --- ', f2(companies, true));
21-
224
// -----------------------------------------------------------------------------
235
// INSTRUCTIONS IN ENGLISH
246

@@ -45,3 +27,21 @@ console.log('---- EXAMPLE 2 --- ', f2(companies, true));
4527
// "users" dont la valeur de l'attribut "car" est égal au paramètre de la
4628
// fonction "hasCar" et l'attribut "usersLength" doit renseigner le nombre de
4729
// "users" correspondant au paramètre "hasCar".
30+
31+
export default function f2(companies, hasCar) {
32+
return companies.map(
33+
(company) => {
34+
const users = company.users.filter(
35+
(u) => (u.car === hasCar),
36+
);
37+
38+
return {
39+
...company,
40+
users,
41+
usersLength: users.length,
42+
};
43+
});
44+
};
45+
46+
cleanConsole(2, companies);
47+
console.log('---- EXAMPLE 2 --- ', f2(companies, true));

example-3.js

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,41 @@ import f1 from './example-1';
44

55
const companies = createAll();
66

7+
// -----------------------------------------------------------------------------
8+
// INSTRUCTIONS IN ENGLISH
9+
10+
// Create a function taking the "companies" variable as a parameter and returning
11+
// a boolean validating that all the names of the companies and the attributes "firstName"
12+
// and "lastName" of "users" are capitalized. You must test the operation
13+
// of this function by importing the function created for "example-1.js".
14+
15+
// -----------------------------------------------------------------------------
16+
// INSTRUCCIONES EN ESPAÑOL
17+
18+
// Cree una función tomando la variable "companies" como parámetro y devolviendo
19+
// un booleano que valida que todos los nombres de las empresas y los atributos
20+
// "firstName" y "lastName" de "users" están en mayúsculas.
21+
// Debes probar la operación de esta función importando la función creada
22+
// en el "example-1.js".
23+
24+
// -----------------------------------------------------------------------------
25+
// INSTRUCTIONS EN FRANÇAIS
26+
27+
// Créer une fonction prenant en paramètre la variable "companies" et renvoyant
28+
// un booléen validant que tous les noms des "company" et les attributs "firstName"
29+
// et "lastName" des "users" sont en majuscules. Vous devez tester le fonctionnement
30+
// de cette fonction en important la fonction créée pour "example-1.js".
31+
732
const isCapitalized = (s) => (s.charAt(0) === s.charAt(0).toUpperCase());
833

934
const f3 = (companies, hasCar) => {
1035
return (
1136
companies.find(
1237
(company) => {
1338
// Check company name
14-
if (!isCapitalized(company.name)) return true;
39+
if (
40+
!isCapitalized(company.name)
41+
) return true;
1542

1643
return (
1744
company.users.find(
@@ -45,28 +72,3 @@ const f3 = (companies, hasCar) => {
4572

4673
cleanConsole(3, companies);
4774
console.log('---- EXAMPLE 3 --- ', f3(companies), f3(f1(companies)));
48-
49-
// -----------------------------------------------------------------------------
50-
// INSTRUCTIONS IN ENGLISH
51-
52-
// Create a function taking the "companies" variable as a parameter and returning
53-
// a boolean validating that all the names of the companies and the attributes "firstName"
54-
// and "lastName" of "users" are capitalized. You must test the operation
55-
// of this function by importing the function created for "example-1.js".
56-
57-
// -----------------------------------------------------------------------------
58-
// INSTRUCCIONES EN ESPAÑOL
59-
60-
// Cree una función tomando la variable "companies" como parámetro y devolviendo
61-
// un booleano que valida que todos los nombres de las empresas y los atributos
62-
// "firstName" y "lastName" de "users" están en mayúsculas.
63-
// Debes probar la operación de esta función importando la función creada
64-
// en el "example-1.js".
65-
66-
// -----------------------------------------------------------------------------
67-
// INSTRUCTIONS EN FRANÇAIS
68-
69-
// Créer une fonction prenant en paramètre la variable "companies" et renvoyant
70-
// un booléen validant que tous les noms des "company" et les attributs "firstName"
71-
// et "lastName" des "users" sont en majuscules. Vous devez tester le fonctionnement
72-
// de cette fonction en important la fonction créée pour "example-1.js".

example-4.js

Lines changed: 36 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,15 @@
11
import {cleanConsole, createAll} from './data';
2-
const companies = createAll();
3-
4-
export default function f4(cs) {
5-
// Get all users to one table
6-
let users = cs.map((c) => {
7-
return c.users.map((u) => ({
8-
...u,
9-
company: c.name,
10-
}));
11-
});
12-
13-
users = users.flat();
142

15-
// Sort them by age desc
16-
users = users.sort(function(a, b) {
17-
return b.age - a.age;
18-
});
3+
const companies = createAll();
194

20-
return users;
21-
};
5+
// -----------------------------------------------------------------------------
6+
// INSTRUCTIONS IN ENGLISH
227

23-
cleanConsole(4, companies);
24-
console.log('---- EXAMPLE 4 --- ', f4(companies));
8+
// Create a function taking as parameter the "companies" variable and grouping
9+
// all "users" of all "companies" in a single table. Each "user"
10+
// must have a new attribute "company" having for value the name of the "company"
11+
// to which it belongs. The "users" must be sorted according to their
12+
// age (from oldest to youngest).
2513

2614
// -----------------------------------------------------------------------------
2715
// INSTRUCCIONES EN ESPAÑOL
@@ -32,15 +20,6 @@ console.log('---- EXAMPLE 4 --- ', f4(companies));
3220
// dicha "company". Los "users" deben ordenarse de acuerdo con sus edad
3321
// (de mayor a menor).
3422

35-
// -----------------------------------------------------------------------------
36-
// INSTRUCTIONS IN ENGLISH
37-
38-
// Create a function taking as parameter the "companies" variable and grouping
39-
// all "users" of all "companies" in a single table. Each "user"
40-
// must have a new attribute "company" having for value the name of the "company"
41-
// to which it belongs. The "users" must be sorted according to their
42-
// age (from oldest to youngest).
43-
4423
// -----------------------------------------------------------------------------
4524
// INSTRUCTIONS EN FRANÇAIS
4625

@@ -49,3 +28,31 @@ console.log('---- EXAMPLE 4 --- ', f4(companies));
4928
// doit avoir un nouvel attribut "company" ayant pour valeur le nom de la "company"
5029
// à laquelle il appartient. Les "users" doivent être triés en fonction de leur
5130
// âge (du plus vieux au plus jeune).
31+
32+
export default function f4(cs) {
33+
// Get all users to one table
34+
let users = cs.reduce(
35+
(accumulator, c) => {
36+
return [
37+
...accumulator,
38+
...c.users.map(
39+
(u) => ({
40+
...u,
41+
company: c.name,
42+
}),
43+
),
44+
];
45+
},
46+
[],
47+
);
48+
49+
// Sort them by age desc
50+
users = users.sort(
51+
(a, b) => (b.age - a.age),
52+
);
53+
54+
return users;
55+
};
56+
57+
cleanConsole(4, companies);
58+
console.log('---- EXAMPLE 4 --- ', f4(companies));

example-5.js

Lines changed: 35 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,16 @@
11
import {cleanConsole, createAll} from './data';
22
const companies = createAll();
33

4-
import f4 from './example-4';
5-
6-
const getAvg = (ages) => (ages.reduce((a, b) => a + b, 0) / ages.length);
7-
8-
export default function f5(us) {
9-
// 'average' => average age of "users"
10-
const ages = us.map((u) => u.age);
11-
const ageAvg = getAvg(ages);
12-
13-
// 'hasCar' => number of "users" owning a car
14-
const usersWithCar = us.filter((u) => (u.car === true));
15-
16-
return {
17-
'size': us.length,
18-
'average': ageAvg,
19-
'hasCar': usersWithCar.length,
20-
'averageWithCar': getAvg(usersWithCar.map((u) => u.age)),
21-
};
22-
}
4+
// -----------------------------------------------------------------------------
5+
// INSTRUCTIONS IN ENGLISH
236

24-
cleanConsole(5, companies);
25-
console.log('---- EXAMPLE 5 --- ', f5(f4(companies)));
7+
// Use the function created in example 4 to create a
8+
// new function taking as parameter the "companies" variable and returning
9+
// a new object with the following attributes:
10+
// 'size' => number of "users"
11+
// 'average' => average age of "users"
12+
// 'hasCar' => number of "users" owning a car
13+
// 'averageWithCar' => average age of users with a car
2614

2715
// -----------------------------------------------------------------------------
2816
// INSTRUCCIONES EN ESPAÑOL
@@ -35,17 +23,6 @@ console.log('---- EXAMPLE 5 --- ', f5(f4(companies)));
3523
// 'hasCar' => total de "users" propietarios de un carro
3624
// 'averageWithCar' => edad promedio de los "users" con un carro
3725

38-
// -----------------------------------------------------------------------------
39-
// INSTRUCTIONS IN ENGLISH
40-
41-
// Use the function created in example 4 to create a
42-
// new function taking as parameter the "companies" variable and returning
43-
// a new object with the following attributes:
44-
// 'size' => number of "users"
45-
// 'average' => average age of "users"
46-
// 'hasCar' => number of "users" owning a car
47-
// 'averageWithCar' => average age of users with a car
48-
4926
// -----------------------------------------------------------------------------
5027
// INSTRUCTIONS EN FRANÇAIS
5128

@@ -56,3 +33,29 @@ console.log('---- EXAMPLE 5 --- ', f5(f4(companies)));
5633
// 'average' => moyenne d'âge des "users"
5734
// 'hasCar' => nombre de "users" possédant une voiture
5835
// 'averageWithCar' => moyenne d'âge des "users" possédant une voiture
36+
37+
import f4 from './example-4';
38+
39+
const getAvg = (ages) => (ages.reduce((a, b) => a + b, 0) / ages.length);
40+
41+
export default function f5(us) {
42+
// Gets 'average' => average age of "users"
43+
const ages = us.map((u) => u.age);
44+
45+
// Gets 'hasCar' => number of "users" owning a car
46+
const usersWithCar = us.filter(
47+
(u) => (u.car === true),
48+
);
49+
50+
return {
51+
'size': us.length,
52+
'average': getAvg(ages),
53+
'hasCar': usersWithCar.length,
54+
'averageWithCar': getAvg(usersWithCar.map(
55+
(u) => u.age),
56+
),
57+
};
58+
}
59+
60+
cleanConsole(5, companies);
61+
console.log('---- EXAMPLE 5 --- ', f5(f4(companies)));

0 commit comments

Comments
 (0)