Run a list of functions and get a list of results:
Hi, I'm a new programmer!
I've been studying for a few months and would like to share this piece of code that came to mind when I studied about the Reduce() function.
I know it's something simple, but it could be useful for many people to extend it, comment on it and improve it.
// Run with Node 11 or higher
// DATA-COLLECTING FUNCTIONS
const func1 = () => { return { user: 'Diego Perdomo' } }
const func2 = () => { return { skills: ['Js', 'React', 'Node', 'Sql'] } }
const func3 = () => { return { webs: ['dpercode.com', 'dev.to/diegoper'] } }
const func4 = () => { return { articles: ['My Article 1', 'My Article 2'] } }
// CREATE ARRAY OF FUNCTIONS
const myFunctions = [func1, func2, func3, func4]
// REDUCE THE FUNCTIONS
const funcReducer = myFunctions.reduce((funcAccumulator, nextFunc) => {
let arrayFunc = [];
funcAccumulator === undefined ?
arrayFunc.push(nextFunc()) :
arrayFunc.push(funcAccumulator, nextFunc())
return arrayFunc.flat();
}, undefined)
// RESULTS
console.log(funcReducer)
// RESULT
[
{ user: 'Diego Perdomo' },
{ skills: [ 'Js', 'React', 'Node', 'Sql' ] },
{ webs: [ 'dpercode.com', 'dev.to/diegoper' ] },
{ articles: [ 'My Article 1', 'My Article 2' ] }
]
Thanks for visiting my article...
Top comments (2)
Hey Diegoper. That's an interesting approach. However, I think that a map would be more appropriate in this case:
Hahaha it's good... Thanks