I posted an answer on StackOverflow which I believed to be adherent to the principles of Functional Programming.
However, I was told by the original asker that it was not 'functional' as my function used an internal variable oldData
which kept track of results.
I believe that the code still satisfies the paradigms of functional programming as it does not mutate it's arguments, does not use globals and has no side effects (assuming action
is not a network call)
Is the function process()
violating the principles of functional programming? If so, how would I fix it?
var items = [
["item1", "item2"],
["item3", "item4"],
["item5", "item6"],
["item7", "item8"],
["item9", "item10"]
]
function action(item) {
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(item + ":processed");
}, 100)
});
}
function process(items) {
return items.reduce((m, d) => {
const promises = d.map(i => action(i));
let oldData;
return m.then((data) => {
oldData = data;
return Promise.all(promises);
})
.then(values => {
//oldData.push(...values);
oldData.push.apply(oldData, values);
return Promise.resolve(oldData);
})
}, Promise.resolve([]))
}
process(items).then(d => console.log(d))
//Prints:
// ["item1:processed","item2:processed","item3:processed","item4:processed","item5:processed","item6:processed","item7:processed","item8:processed","item9:processed","item10:processed"]
The original asker suggested that I update my code to use concat
instead of push
to create immutable arrays every time to make this properly functional. Does that make sense?