nonlogos
12/11/2017 - 2:28 PM

optional reduce arguments patterns

optional reduce arguments patterns

function reducer(accumulator, value, index, array) {
  var intermediaryValue = accumulator + value;
  
  // at the end of the array iteration, perform additional logic
  if (index === array.length - 1) {
    return intermediaryValue / array.length;
  }
  // else just return the iterated value
  return intermediaryValue;
}

// how to use it with array.reduce

var data = [1,2,3,4,5,2,1];
var medium = data.reduce(reducer, 0);
// data structure
var data = [
  {
    name: 'han solo',
    jedi: false,
    parents: {
      father: {
        jedi: false
      }, 
      mother: {
        jedi: true
      }
    }
  },
  {
    name: 'anakin',
    jedi: true,
    parents: {
      mother: {
        jedi: true
      } // missing the father nested property
    }
  },
  ...
]

// returns the value if the nested property exists, else returns false
function fatherWasJedi(character) {
  var path = 'parents.father.jedi';
  return path.split('.').reduce((obj, field) => {
    if (obj) {
      return obj[field];
    }
    return false;
  }, character)
}

data.forEach(character => { return fatherWasJedi(character); })
function increment(input) {return input + 1}
function decrement(input) {return input - 1}
function double(input) {return input * 2}

var initial_value = 1;

// put a chain of functions in a pipeline array
var pipeline = [
  increment,
  double,
  decrement
];

//use reduce to call each function by order of the array and pass in the previous computed result
var final_value = pipeline.reduce((acc, fn) => {
  return fn(acc);
}, initial_value);

// or use reduceRight to reverse the function call order to start from the right
var final_value = pipeline.reduceRight((acc, fn) => {
  return fn(acc);
}, initial_value); // decrement will be called first instead of increment