Solving Eloquent Javascript exercise

2018-02-02 21:28:43

I solved an exercise from the book "Eloquent Javascript". I want to share with you guys the solution. The exercise is from chapter 5. Summing up, I have to find the average age from the ancestors array per century. Here is my solution:

var ancestry = JSON.parse(require('../resources/ancestry'))

//Top-down approach, functions are defined after their use

//Necessary side-effect in function to print the output

function printAverageAgePerCentury(ancestry){

var averageAgePerCentury = getAverageAgePerCentury(ancestry);

Object.keys(averageAgePerCentury).forEach(function(century){

console.log(century.concat(": ").concat(averageAgePerCentury[century]))

})

}

function getAverageAgePerCentury(ancestry){

var agesPerCentury = getAgesPerCentury(ancestry);

return agesPerCentury.reduce(function(averageAgePerCentury, agePerCentury){

if(averageAgePerCentury[agePerCentury.century]){

averageAgePerCentury[agePerCentury.century] = [average(av