Working with ranges

Let's now turn to a helper function, which will come in handy for many uses. We want a range(start,stop) function that generates an array of numbers, with values ranging from start (inclusive) to stop (exclusive):

const range = (start, stop) =>  new Array(stop - start).fill(0).map((v, i) => start + i);let from2To6 = range(2, 7); // [2, 3, 4, 5, 6]

Why fill(0)? All undefined array elements are skipped by map(), so we need to fill them with something or our code will have no effect.

Libraries such as Underscore and Lodash provide a more powerful version of our range function, letting you go in ascending or descending order and also specifying the step to use—as in _.range(0, -8, -2), which produces [0, -2, -4, -6]—but for ...

Get Mastering JavaScript Functional Programming - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.