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).
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);