erikpalla
3/5/2017 - 9:48 PM

Reduce (Usage examples) Source: https://medium.freecodecamp.com/reduce-f47a7da511a9#.g6he8i9z5

//Example 1: reduce - hashmap
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

const count = fruitBasket.reduce( (tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1 ;
  return tally;
} , {})

count // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

//***

//Example 2: reduce unique items
const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

const uniqueColors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
    if (total.indexOf(color) === -1){
     total.push(color);
    }
  });
  return total;
}, []);
uniqueColors // [ 'blue', 'red', 'green', 'black', 'orange']

//***

//Example 3: Reduce fn() - pipeline
const pipeline = [increment, double, decrement];

const result = pipeline.reduce(function(total, fn) {
  return fn(total);
}, 1);
result // 3
//***

//Example with reduce spread operator
const heroes = [
    {name: 'Hulk', strength: 90000, sex: 'm'},
    {name: 'Spider-Man', strength: 25000, sex: 'm'},
    {name: 'Hawk Eye', strength: 136, sex: 'm'},
    {name: 'Thor', strength: 100000, sex: 'm'},
    {name: 'Black Widow', strength: 136, sex: 'f'},
    {name: 'Vision', strength: 5000, sex: 'm'},
    {name: 'Scarlet Witch', strength: 60, sex: 'f'},
    {name: 'Mystique', strength: 120, sex: 'f'},
    {name: 'Namora', strength: 75000, sex: 'f'},
];

function greaterStrength(champion, contender) {
    return (contender.strength > champion.strength) ? contender : champion;
}

function addStrength(tally, hero) {
    return tally + hero.strength;
}


function processStrength({strongestHero, combinedStrength}, hero) {
    return {
        strongestHero: greaterStrength(strongestHero, hero),
        combinedStrength: addStrength(combinedStrength, hero),
    };
}
const {strongestHero, combinedStrength} = heroes.reduce(processStrength, {strongestHero: {strength: 0}, combinedStrength: 0});