This is an example from "Eloquent JavaScript" book (I think you know the book):
function groupBy(array, groupOf) {
var groups = {};
array.forEach(function(element) {
var groupName = groupOf(element);
if (groupName in groups)
groups[groupName].push(element);
else
groups[groupName] = [element];
});
return groups;
}
var byCentury = groupBy(ancestry, function(person) {
return Math.ceil(person.died / 100);
});
What the code does is not very important.
The question is: the groupBy
function has two different 'bodies', i.e. it does completely different things, as far as I can see. In the first instance, it does a lot of logic, but the second time it, first, has a different second argument (function(person)
instead of groupOf
, and, second, it just divides an array element property (which is the date of death of a person in an array of 39 people) by 100.
How can it be that the same function does different things? I do understand that
these two instances of the same function somehow cooperate, but what is the general principle of such cooperation?
Thank you!