Unlicensed-7-PDF107-108_Eloquent_JavaScript

advertisement
Transforming with map
Say we have an array of objects representing people, produced by filtering
the ancestry array somehow. But we want an array of names, which is
easier to read.
The map method transforms an array by applying a function to all of its
elements and building a new array from the returned values. The new
array will have the same length as the input array, but its content will
have been "mapped" to a new form by the function.
function map(array , transform) {
var mapped = [];
for (var i = 0; i < array.length;
mapped.push(transform(array[i]));
return mapped;
}
var
i++)
overNinety = ancestry.filter(function(person)
return person.died - person.born > 90;
{
});
console.log(map(overNinety , function(person) {
return person.name;
}));
//  [" Clara Aernoudts", "Emile Haverbeke",
//
"Maria Haverbeke "]
Interestingly, the people who lived to at least 90 years of age are the
same three people who we saw before—the people who were young in
the 1920s, which happens to be the most recent generation in my data
set. I guess medicine has come a long way.
Like forEach and filter, map is also a standard method on arrays.
Summarizing with reduce
Another common pattern of computation on arrays is computing a single value from them. Our recurring example, summing a collection of
numbers, is an instance of this. Another example would be finding the
person with the earliest year of birth in the data set.
The higher-order operation that represents this pattern is called reduce
95
(or sometimes fold). You can think of it as folding up the array,
one
element at a time. When summing numbers, you'd start with the number
zero and, for each element, combine it with the current sum by adding
the two.
The parameters to the reduce function are, apart from the array, a combining function and a start value. This function is a little less straightforward than filter and map, so pay careful attention.
function reduce(array , combine , start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current , array[i]);
return current;
}
console.log(reduce ([1,
return a + b;
}, 0));
// 10
2,
3,
4],
function(a,
b)
{
The standard array method reduce, which of course corresponds to this
function, has an added convenience. If your array contains at least one
element, you are allowed to leave of the start argument. The method
will take the first element of the array as its start value and start reducing
at the second element.
To use reduce to find my most ancient known ancestor, we can write
something like this:
console.log(ancestry.reduce(function(min , cur)
if (cur.born < min.born) return cur;
else return min;
}));  {name: "Pauwels van Haverbeke",
//
{
born:
1535,
...}
Composability
Consider how we would have written the previous example (finding the
person with the earliest year of birth) without higher-order functions.
The code is not that much worse.
96
Download