Skip to Content
Mastering JavaScript Functional Programming - Second Edition
book

Mastering JavaScript Functional Programming - Second Edition

by Federico Kereki
January 2020
Intermediate to advanced
470 pages
11h 13m
English
Packt Publishing
Content preview from Mastering JavaScript Functional Programming - Second Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming

Federico Kereki

Publisher Resources

ISBN: 9781839213069Supplemental Content