@@ -52,4 +52,42 @@ console.log('----- TEST 1 -----');
5252checkDogs ( dogsJulia1 , dogsKate1 ) ;
5353
5454console . log ( '----- TEST 2 -----' ) ;
55- checkDogs ( dogsJulia2 , dogsKate2 ) ;
55+ checkDogs ( dogsJulia2 , dogsKate2 ) ;
56+
57+ // Coding Challenge 2
58+
59+ /*
60+ Create a function 'calcAverageHumanAge', which accepts an arrays of dog's
61+ ages ('ages'), and does the following things in order:
62+ 1. Calculate the dog age in human years using the following formula: if the dog is
63+ <= 2 years old, humanAge = 2 * dogAge. If the dog is > 2 years old,
64+ humanAge = 16 + dogAge * 4
65+ 2. Exclude all dogs that are less than 18 human years old (which is the same as
66+ keeping dogs that are at least 18 years old)
67+ 3. Calculate the average human age of all adult dogs (you should already know
68+ from other challenges how we calculate averages 😉)
69+ 4. Run the function for both test datasets
70+ Test data:
71+ § Data 1: [5, 2, 4, 1, 15, 8, 3]
72+ § Data 2: [16, 6, 10, 5, 6, 1, 4]
73+ */
74+
75+ const dogsAge1 = [ 5 , 2 , 4 , 1 , 15 , 8 , 3 ] ;
76+ const dogsAge2 = [ 16 , 6 , 10 , 5 , 6 , 1 , 4 ] ;
77+
78+ const calcAverageHumanAge = ages =>
79+ {
80+ const humanYears = ages . map ( curr => ( curr <= 2 ) ? curr * 2 : 16 + curr * 4 ) ;
81+ const humanYearsFiltered = humanYears . filter ( curr => curr >= 18 ) ;
82+ console . log ( humanYearsFiltered ) ;
83+
84+ let avr = humanYearsFiltered . reduce ( ( acc , curr ) => acc += curr , 0 ) ;
85+ avr /= humanYearsFiltered . length ;
86+ console . log ( `Average of Human Years: ${ avr } ` ) ;
87+ } ;
88+
89+ console . log ( '----- TEST 1 -----' ) ;
90+ calcAverageHumanAge ( dogsAge1 ) ;
91+
92+ console . log ( '----- TEST 2 -----' ) ;
93+ calcAverageHumanAge ( dogsAge2 ) ;
0 commit comments