Reputation: 1957
Lets say I have an array of functions as below
var updateCountryToCanada = function (items) {
return items.map(i => {i['country'] = 'Canada'; return i});
}
var strip_punctuation_from_name = function (items) {
return items.map(i => {i['name'] = i['name'].replace('.', '-');
return i});
}
and an array of items as below
var items = [{'name': 'John.Joo', 'height': 160, 'country':'US'},
{'name': 'Isla', 'height': 180, 'country':'France'},
{'name': 'Sam'}];
I put all my functions in an array
var funcs = [updateCountryToCanada, strip_punctuation_from_name]
Now, my question is how can I in JavaScript call functions one at a time and pass all items to them in a way that the result of the first function become the input to the second and so on? I want to chain them together (piping).
Upvotes: 0
Views: 351
Reputation: 150080
You can use the .reduce()
method:
var result = funcs.reduce((r, f) => f(r), items);
This calls the (r, f) => f(r)
function for each item in the funcs
array. The first time, r
will be items
. For each subsequent one r
will be whatever value was returned from the previous call. f
is the current item from funcs
.
Expand the snippet to see the results:
var updateCountryToCanada = function (items) {
return items.map(i => {i['country'] = 'Canada'; return i});
}
var strip_punctuation_from_name = function (items) {
return items.map(i => {i['name'] = i['name'].replace('.', '-');
return i});
}
var items = [{'name': 'John.Joo', 'height': 160, 'country':'US'},
{'name': 'Isla', 'height': 180, 'country':'France'}];
var funcs = [updateCountryToCanada, strip_punctuation_from_name];
var result = funcs.reduce((r, f) => f(r), items);
console.log(result);
Upvotes: 4
Reputation: 29501
As a relatively simple approach, you can call:
functionOne();
If functionOne()
looks something like:
function functionOne() {
[... CODE ...]
var result = [...WHATEVER...];
functionTwo(result);
}
and functionTwo()
then looks something like:
function functionTwo(input) {
var input = input;
[... CODE ...]
var result = [...WHATEVER...];
functionThree(result);
}
Then the result of functionOne()
will be the input of functionTwo()
, the result of functionTwo()
will be the input of functionThree()
etc.
Upvotes: 0
Reputation: 7360
This solution is not properly piping (as >
or |
in Unix), but you can do something like this:
for (i = 0; i < funcs.length; i++) {
items = funcs[i](items);
}
var updateCountryToCanada = function (items) {
return items.map(i => {i['country'] = 'Canada'; return i});
}
var strip_punctuation_from_name = function (items) {
return items.map(i => {i['name'] = i['name'].replace('.', '-'); return i});
}
var items = [{'name': 'John.Joo', 'height': 160, 'country':'US'},
{'name': 'Isla', 'height': 180, 'country':'France'},
{'name': 'Sam'}];
var funcs = [updateCountryToCanada, strip_punctuation_from_name];
for (i = 0; i < funcs.length; i++) {
items = funcs[i](items);
}
console.log(items)
Upvotes: 0