3

I'm trying to write code in a more functional style, and a problem I keep encountering is populating an array of n items.

For example:

const items[];

for (let i = 0; i < n; i++) {
    items.push(new Item());
}

If I understand correctly, there are two side effects here: i is mutating and items is as well.

I'm wondering what is the "pure" way to do this in Javascript. I've tried stuff like (new Array(n)).map(...) and (new Array(n)).forEach(...) but I'm not sure why these would be better or worse. Can someone elaborate, or point me to a post that covers this topic?

Ben
  • 54,723
  • 49
  • 178
  • 224
  • 5
    A mutating local variable that is not seen externally is perfectly acceptable in functional style. – mellamokb Apr 19 '16 at 14:32
  • 1
    You can use `Array.prototype.fill()` instead. – Redu Apr 19 '16 at 14:32
  • 3
    @Redu: If you use that with an object reference (e.g., `new Item()`), you will end up with `n` copies of the same instance, instead of `n` separate instances... – mellamokb Apr 19 '16 at 14:32
  • 1
    @mellamokb you are right of course but that's not what i mean. What i wanted to say was, as mentioned in the question Array map or Array forEach wouldn't iterate over new Array(n) since it's items are undefined. Has to be like `(new Array(n)).fill("You got it?").map(e => new Item())` – Redu Apr 19 '16 at 14:57
  • @mellamokb: That shouldn't matter, given the OP is interested in functional programming :-) – Bergi Apr 19 '16 at 14:57

1 Answers1

2

This solution seems like a good option:

const n = 10;
const items = Array.from(Array(n), x => new Item());

Check more about the Array.from().


This article gives a good level of details for functional programming in Javascript.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41