Functional Programming — The Examples Series — Initializing An Array With Random Data

This is the 3rd article in my “examples series” for functional programming. Read about the series here, including links to previous and future examples.

I am working on a three dimensional timeline with three.js. The idea is that you can “drive into the past” down a road with signposts showing events as you go. I’m in the early stages and when I’m just starting out, I tend to create batches of random data. Here’s the imperative appraoch:

Class, imperative appraoch to populating an array

This is classic:

  • Initialize an Array of 3d Timelines
  • Define a counter variable (i) and iterate.
  • Create an instance of the object and push it into the array.

Here it is in a more functional style:

More Functional Style Array Population

In the functional style, I use “_range” instead for for/each and declared counter variable i. I map over that range, passing in the counter and then use that counter to calculate a Z position for a graphical object (just like in the imperative version).

The functional style includes some of the same code as its imperative cousin, but overall, it does less work. It doens’t need to initialize the array since the _map function returns the array directly. There’s no “push” (at least here) and therefore no real chance to push the wrong thing by accident. There’s no one-time-use counter variable.

Is this better? Probably. Once you get the hang of “, end), (counter) => {})” it gells. At least for me :).


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.