compose functions with 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 = [ ///behavior we want to capture (in the order we want to use them)
increment,
increment,
increment,
double,
increment,
increment,
halve
];
var final_value = pipeline.reduce(function(acc, fn) { ///starts at pipeline[0]
return fn(acc);
}, initial_value);
var reversed = pipeline.reduceRight(function(acc, fn) { ///starts at the last value and work BACKWARDS
return fn(acc);
}, initial_value)
final_value
reversed
This Gist was automatically created by Carbide, a free online programming environment.