Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active October 16, 2015 01:56
Show Gist options
  • Save stonehippo/16a8e1a909e5bcbf112d to your computer and use it in GitHub Desktop.
Save stonehippo/16a8e1a909e5bcbf112d to your computer and use it in GitHub Desktop.
Reduce: the power of a higher-order function
/*
A quick demo of the power of the `reduce()` higher-order function.
In this demo, `reduce()` has been used to replicate several of its
higher-order cousins: `map()`, `filter()`, and `find()`. The point is
to show that `reduce()` is a functional multi-tool. If you have
`reduce()``, you're on your way to some functional bliss.
For each example, the native version of the higher-order function is
shown before the reduce version. The native versions are much more
concise, of course. The point is to show that they're not _required_,
even though they're _preferred_.
This example makes use of a couple of ES6/ES2015 features, namely arrow
functions and `let`. Therefore, you'll want to use something like babel
or the latest (4.x+) versions of node.js if you try this out.
*/
'use strict';
let arr = [
{
name: "Fred",
age: 43,
species: "human"
},
{
name: "Mary",
age: 48,
species: "human"
},
{
name: "Cal",
age: 9,
species: "human"
},
{
name: "Purrf",
age: 10,
species: "cat"
},
{
name: "Toots",
age: 2,
species: "dog"
}
];
// var humans = arr.filter((member) => member.species === "human");
// reduce as filter
let humans = arr.reduce(function(sum, member){
if (member.species === "human") {
sum.push(member);
}
return sum;
}, []);
console.log(humans);
// var names = arr.map((member) => member.name);
// reduce as map
let names = arr.reduce(function(sum, member) {
sum.push(member.name);
return sum;
}, []);
console.log(names);
// var firstDog = arr.find((member) => member.species === "dog");
// reduce as find
let firstDog = arr.reduce(function(sum, member) {
if (!sum && member.species === "dog") {
sum = member;
}
return sum;
}, undefined);
console.log(firstDog);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment