Skip to content

Instantly share code, notes, and snippets.

@spamwax
Last active November 22, 2017 22:34
Show Gist options
  • Save spamwax/99f1a2d9f21ed463d157 to your computer and use it in GitHub Desktop.
Save spamwax/99f1a2d9f21ed463d157 to your computer and use it in GitHub Desktop.
Solution to eloquentjavascript exercise second 2nd edition (Chapter 5) eloquent javascript
// Solution to eloquentjavascript exercise second 2nd edition
// Chapter 5
// http://eloquentjavascript.net/2nd_edition/preview/05_higher_order.html
// Mother-child age difference
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
var byName = {};
console.log(typeof ancestry)
ancestry.forEach(function(person) {
byName[person.name] = person;
});
// Your code here.
var hasKnownMother = function(person) {
return person.mother in byName;
};
function getAgeDiff(person) {
return person.born - byName[person.mother].born
}
console.log(average(ancestry.filter(hasKnownMother).map(getAgeDiff)));
// → 31.2
// ---------------------------------------
// Flattening
console.log(arrays.reduce(function(res, nextItem) {
return res.concat(nextItem);} ));
// ---------------------------------------
// Historical life expectancy
var perCentury = {};
ancestry.forEach(function(person) {
var cent = String(Math.ceil(person.died/100));
if (!(cent in perCentury)) {
perCentury[cent] = [];
}
perCentury[cent].push(person.died - person.born);
});
for (cent in perCentury) {
console.log(cent, '->', average(perCentury[cent]));
}
// bonus
function groupBy(a, classifyFunc) {
return a.map(classifyFunc).reduce(function (curr, item, idx) {
if (!(item in curr)) {
curr[item] = [a[idx]];
} else {
curr[item].push(a[idx]);
}
return curr;
}, {});
}
function byDeathCent(person) {
return String(Math.ceil(person.died/100));
}
var groups = groupBy(ancestry, byDeathCent);
for (cent in groups) {
var avg = average(groups[cent].map(function (person) {
return person.died - person.born;
}));
console.log(cent, '->', avg);
}
// ---------------------------------------
// Every and then some
function every(a, predicate) {
for (var i=0; i< a.length; ++i) {
if (!(predicate(a[i]))) {
return false
}
}
return true;
}
function some(a, predicate) {
for (var i=0; i< a.length; ++i) {
if (predicate(a[i])) {
return true;
}
}
return false;
}
@Madhurimahajan
Copy link

Very useful! Thanks a lot!

@paulmatheson
Copy link

Very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment