forked from CUNYTechPrep/eloquentjs-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchapter05.js
More file actions
65 lines (56 loc) · 1.7 KB
/
Copy pathchapter05.js
File metadata and controls
65 lines (56 loc) · 1.7 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
/*
* Add your solutions to the chapter 5 problems from the eloquentjs book.
* - DO NOT rename the functions below.
* - You may add other functions if you need them.
* - You may rename the parameters.
* - DO NOT modify the number of parameters for each function.
*/
const ancestry = require('./ancestry');
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
const byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});
// Problem 1: Flattening
function flatten(arrays) {
// Your code here
return arrays.reduce(function(flat, current) {
return flat.concat(current);
});
}
// Problem 2: Mother-child age difference
/* This must return the average age difference instead of printing it */
function averageMomChildAgeDiff() {
// Your code here
var hasKnownMother = ancestry.filter(function(person){
return person.mother !== null && person.mother in byName;
});
var diff = hasKnownMother.map(function(person){
return person.born - byName[person.mother].born;
});
return(average(diff));
}
// Problem 3: Historical life expectancy
/* This must return the object/map with centuries as keys and average age
for the century as the value
*/
function averageAgeByCentury() {
// Your code here
var centuries = {};
ancestry.forEach(function(person){
var century = Math.ceil(person.died/100);
if(!(century in centuries)) {
centuries[century] = [];
}
centuries[century].push(person.died - person.born);
});
for(var i in centuries) {
centuries[i] = average(centuries[i]);
};
return centuries;
}
// Do not modify below here.
module.exports = { flatten, averageMomChildAgeDiff, averageAgeByCentury };