What I want to do is return an array of objects based a dynamic size, I feel like I might be doing this in an overly complicated way but i’m also trying to do things in a more functional manner these days.
Here is how I would do it in the non-functional manner
function nonFunctional(size) {
let foo = [];
for (let index = 0; index < size; index++) {
foo.push({ bar: "baz" });
}
return foo;
}
Here is how i’m trying to do it in a Functional manner
function functional(size) {
return [...new Array(size)].map(() => {
return {
bar: 'baz'
}
});
}
- Is this the best way to do this in a functional way?
- What are some advantages/disadvantages of doing it this way vs the "traditional" way?
- Is this really even functional programming related?
return Array(size).fill({ bar: "baz" });map, i.e. a function without arguments. In FP in conjunction with a strict evaluated language explicit thunks are only used to obtain lazyness. Also in Javascript with its lack of a type system and the guarantees such a system entails, you can apply mutations locally, so that they are not observable in the parent scope.