Last active
December 11, 2017 14:42
-
-
Save nonlogos/365d5f9fb8ee0dc3ac5ae043330216c5 to your computer and use it in GitHub Desktop.
optional reduce arguments patterns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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