Skip to content

Instantly share code, notes, and snippets.

@nonlogos
Last active December 11, 2017 14:42
Show Gist options
  • Save nonlogos/365d5f9fb8ee0dc3ac5ae043330216c5 to your computer and use it in GitHub Desktop.
Save nonlogos/365d5f9fb8ee0dc3ac5ae043330216c5 to your computer and use it in GitHub Desktop.
optional reduce arguments patterns
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
// 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 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment