Skip to content

Instantly share code, notes, and snippets.

@SherryH
Last active June 6, 2018 22:29
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 SherryH/8f6a37286c3253e00223c62dcfc6aba5 to your computer and use it in GitHub Desktop.
Save SherryH/8f6a37286c3253e00223c62dcfc6aba5 to your computer and use it in GitHub Desktop.
// composing functions using reduce
function increment(input) { return input + 1;}
function decrement(input) { return input - 1; }
function double(input) { return input * 2; }
function halve(input) { return input / 2; }
var initial_value = 1;
var pipeline = [
increment,
increment,
increment,
double,
increment,
increment,
halve
];
var final_value = pipeline.reduce(function(acc, fn) {
return fn(acc);
}, initial_value);
var reversed = pipeline.reduceRight(function(acc, fn) {
return fn(acc);
}, initial_value)
console.log("final_value: ", final_value)
console.log("reversed: ", reversed)
------------------------------------------
// inspect nested object using reduce
var luke = {
name: "luke skywalker",
jedi: true,
parents: {
father: {
jedi: true
},
mother: {
jedi: false
}
}
}
var han = {
name: "han solo",
jedi: false,
parents: {
father: {
jedi: false
},
mother: {
jedi: false
}
}
}
var anakin = {
name: "anakin skywalker",
jedi: true,
parents: {
mother: {
jedi: false
}
}
}
var characters = [luke, han, anakin];
function fatherWasJedi(character) {
var path = "parents.father.jedi";
return path.split(".").reduce(function(obj, field) {
if (obj) {
return obj[field];
}
return false;
}, character);
}
characters.forEach(function(character) {
console.log(character.name + "'s father was a jedi:", fatherWasJedi(character))
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment