-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch5.js
More file actions
91 lines (78 loc) · 2.03 KB
/
ch5.js
File metadata and controls
91 lines (78 loc) · 2.03 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Flattening
var arrays = [[1, 2, 3], [4, 5], [6]];
function flatten(arr, rest) {
return arr.concat(rest);
}
console.log(arrays.reduce(flatten));
// Mother-Child Age Difference (requires 'ancestry' data from the text)
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
var byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});
var hasKnownMother = ancestry.filter(function(person) {
return byName[person.mother] != null;
});
var ageDifference = hasKnownMother.map(function(person) {
return person.born - byName[person.mother].born;
});
console.log(average(ageDifference));
// → 31.2
// Historical Life Expectancy
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
function groupByCentury(ancestry) {
var byCentury = {};
ancestry.forEach(function(person) {
var century = Math.ceil(person.died / 100);
if (century in byCentury) {
byCentury[century].push(person);
} else {
byCentury[century] = [person];
}
});
return byCentury;
}
var byCentury = groupByCentury(ancestry);
for (var century in byCentury) {
var agesInCentury = byCentury[century].map(function(person) {
return person.died - person.born;
});
console.log('Average Age in the ' + century + 'th Century: ' + average(agesInCentury));
}
// → 16: 43.5
// 17: 51.2
// 18: 52.8
// 19: 54.8
// 20: 84.7
// 21: 94
// Every And Then Some
function every(array, predicateFunction) {
for (var i = 0; i < array.length; i++) {
if (!predicateFunction(array[i])) {
return false;
}
}
return true;
}
function some (array, predicateFunction) {
for (var i = 0; i < array.length; i++) {
if (predicateFunction(array[i])) {
return true;
}
}
return false;
}
console.log(every([NaN, NaN, NaN], isNaN));
// → true
console.log(every([NaN, NaN, 4], isNaN));
// → false
console.log(some([NaN, 3, 4], isNaN));
// → true
console.log(some([2, 3, 4], isNaN));
// → false