Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Created July 7, 2014 03:09
Show Gist options
  • Save hoodwink73/337a59d5d6e498055888 to your computer and use it in GitHub Desktop.
Save hoodwink73/337a59d5d6e498055888 to your computer and use it in GitHub Desktop.
Using Array.reduce to pipeline functions
var Pipeline = function (series, initialInput) {
this.series = series;
this.initial = function () {
return initialInput;
};
this.hasPerformed = false;
};
Pipeline.prototype.addFunction = function (fn, index) {
if (index === undefined) {
this.series.push(fn);
} else {
this.series.splice(index, 0, fn);
}
};
Pipeline.prototype.perform = function () {
var reducer = function (previousValue, currentValue) {
// invoke the previous function in the series to get the result;
var inputForNext = previousValue();
// bind the input to current function
return currentValue.bind(null, inputForNext);
};
this.finalResult = this.series.reduce(reducer, this.initial)();
this.hasPerformed = true;
};
Pipeline.prototype.getResult = function () {
if (this.hasPerformed) {
return this.finalResult;
} else {
this.perform();
return this.finalResult;
}
};
// this is how the implementation works
// pass the initial value as the second argument
// say the price of the good is 100
var series = [tax, serviceTax];
var pipeline = new Pipeline(series, 100);
pipeline.addFunction(formatMoney);
// get the final value
var result = pipeline.getResult();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment