11// Remove the unused code that does not contribute to the final console log
22// The countAndCapitalisePets function should continue to work for any reasonable input it's given, and you shouldn't modify the pets variable.
33
4+ //let's start from top to bottom and logically think through each line
5+
46const pets = [ "parrot" , "hamster" , "horse" , "dog" , "hamster" , "cat" , "hamster" ] ;
7+ //above line is needed because it is used by everything else.
8+
59const capitalisedPets = pets . map ( ( pet ) => pet . toUpperCase ( ) ) ;
10+ // i am removing above line as "capitalisedPets" is not used anywhere else.
11+
612const petsStartingWithH = pets . filter ( ( pet ) => pet [ 0 ] === "h" ) ;
13+ //this line is filters the words starting with "h" and is used later so we keep it.
714
815function logPets ( petsArr ) {
916 petsArr . forEach ( ( pet ) => console . log ( pet ) ) ;
1017}
18+ //i am erasing the above function as "logPets" is not used anywhere else.
1119
1220function countAndCapitalisePets ( petsArr ) {
1321 const petCount = { } ;
22+ //keeping this function, as petCount is used below.
1423
1524 petsArr . forEach ( ( pet ) => {
1625 const capitalisedPet = pet . toUpperCase ( ) ;
@@ -22,7 +31,36 @@ function countAndCapitalisePets(petsArr) {
2231 } ) ;
2332 return petCount ;
2433}
34+ //everything above is needed to count how many of each pets there are.
2535
2636const countedPetsStartingWithH = countAndCapitalisePets ( petsStartingWithH ) ;
37+ //it is used for function call, so needed.
2738
2839console . log ( countedPetsStartingWithH ) ; // { 'HAMSTER': 3, 'HORSE': 1 } <- Final console log
40+ //we wanna see the result of our machinations so we keep it.
41+
42+ //THE FOLLOWING CODE IS THE CLEANED UP VERSION.
43+
44+ const pets = [ "parrot" , "hamster" , "horse" , "dog" , "hamster" , "cat" , "hamster" ] ;
45+
46+ const petsStartingWithH = pets . filter ( ( pet ) => pet [ 0 ] === "h" ) ;
47+
48+ function countAndCapitalisePets ( petsArr ) {
49+ const petCount = { } ;
50+
51+ petsArr . forEach ( ( pet ) => {
52+ const capitalisedPet = pet . toUpperCase ( ) ;
53+
54+ if ( petCount [ capitalisedPet ] ) {
55+ petCount [ capitalisedPet ] += 1 ;
56+ } else {
57+ petCount [ capitalisedPet ] = 1 ;
58+ }
59+ } ) ;
60+
61+ return petCount ;
62+ }
63+
64+ const countedPetsStartingWithH = countAndCapitalisePets ( petsStartingWithH ) ;
65+
66+ console . log ( countedPetsStartingWithH ) ;
0 commit comments