Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created July 12, 2017 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/3f53cb8786b584ae380a4825716a90d4 to your computer and use it in GitHub Desktop.
Save KinoAR/3f53cb8786b584ae380a4825716a90d4 to your computer and use it in GitHub Desktop.
An example of map, reduce, and filter composed to create hero stats.
/* Map, Reduce, Filter - Composing The functions
* Create Warrior classes using the stats below
* Filter Stats above 50 and reduce it to a single value
* called heroStat with the composition of all their stats
*/
const stats = [10, 20, 30, 50, 70, 80];
/* ES5 Example */
//Map stat numbers into class warrior object
const warriors = stats.map(function (element) { return Object.assign({ class: 'Warrior', stat: element }); });
//filter warriors with stats above 50
const heroStats = warriors.filter(function (element) { return element.stat > 50; })
.reduce(function (start, curr) {
//return warrior stats from the beginning of the way
return start.stat + curr.stat;
});
const hero = { class: 'Hero', stat: heroStats };
console.log('Hero Stats', hero); // Hero Stats { class: 'Hero', stat: 150 }
/* ES6 Example */
const warriors2 = stats.map((element) => { return Object.assign({ class: 'Warrior', stat: element }); });
console.log(warriors); // [{class: 'Warrior', stat: 10}, {class: 'Warrior', stat: 20}...]
const heroStats2 = warriors2.filter((element) => element.stat > 50)
.reduce((start, curr) => {
return start.stat + curr.stat;
});
const hero2 = { class: 'Hero', stat: heroStats2 };
console.log(hero2); // { class: 'Hero', stat: 150 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment