-
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathexercise-2.js
More file actions
66 lines (47 loc) · 2.31 KB
/
exercise-2.js
File metadata and controls
66 lines (47 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Remove the unused code that does not contribute to the final console log
// The countAndCapitalisePets function should continue to work for any reasonable input it's given, and you shouldn't modify the pets variable.
// const pets = ["parrot", "hamster", "horse", "dog", "hamster", "cat", "hamster"];
// const capitalisedPets = pets.map((pet) => pet.toUpperCase());
// const petsStartingWithH = pets.filter((pet) => pet[0] === "h");
// function logPets(petsArr) {
// petsArr.forEach((pet) => console.log(pet));
// }
// function countAndCapitalisePets(petsArr) {
// const petCount = {};
// petsArr.forEach((pet) => {
// const capitalisedPet = pet.toUpperCase();
// if (petCount[capitalisedPet]) {
// petCount[capitalisedPet] += 1;
// } else {
// petCount[capitalisedPet] = 1;
// }
// });
// return petCount;
// }
// const countedPetsStartingWithH = countAndCapitalisePets(petsStartingWithH);
// console.log(countedPetsStartingWithH); // { 'HAMSTER': 3, 'HORSE': 1 } <- Final console log
/**
Removed Unused Global Variables: Deleted const capitalisedPets because the array was being processed
but never used anywhere in the script.
Eliminated Dead Code (Functions): Removed the logPets function since it was never called, keeping
the codebase focused only on the required output.
Simplified Internal Logic:
Renamed the function to countPets for brevity.
Replaced the if/else statement inside the forEach loop with a Logical OR shortcut (|| 0). This
handles both initializing the count and incrementing it in a single line.
Optimized Memory Usage: Removed the intermediate variable countedPetsStartingWithH. Instead,
I passed the function call directly into console.log, as the result didn't need to be stored for further use.
Improved Code Scope: Ensured the function uses its local parameter instead of relying on external
global variables.
*/
const pets = ["parrot", "hamster", "horse", "dog", "hamster", "cat", "hamster"];
const petsStartingWithH = pets.filter((pet) => pet[0] === "h");
function countPets(pets) {
const petCount = {};
pets.forEach((pet) => {
const capitalisedPet = pet.toUpperCase();
petCount[capitalisedPet] = (petCount[capitalisedPet] || 0) + 1;
});
return petCount ;
}
console.log(countPets(petsStartingWithH)); // { 'HAMSTER': 3, 'HORSE': 1 } <- Final console log