DEV Community

Cover image for #LearnedToday: range() in JavaScript
Daniel Zotti
Daniel Zotti

Posted on

#LearnedToday: range() in JavaScript

How nice would it be to have a range(start, stop, step) function in JavaScript similar to the native Python function?

const myRange = range(1,4,1)
// [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Let's do it!

Until an official method is created, we can do it ourselves in a "one" line of code using Array.from() method:

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
Enter fullscreen mode Exit fullscreen mode

Examples

// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]

// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

What about range of letters?

Let's try to go further and try to work with letters. Python does not have a native function to do this either, but thanks to JavaScript methods charCodeAt() and fromCharCode() we can achieve our goal with some minor modifications!

The idea is to convert the letters to UTF-16 char code (aka numbers) to create the range and eventually convert them back to letters:

range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
// ["A", "B", "C", "D", "E",  ..., "X", "Y", "Z"]
Enter fullscreen mode Exit fullscreen mode

Thus our reusable function could be updated this way:

const range = (start, stop, step) => {
  const isString = typeof start === 'string' && typeof stop === 'string';

  if (isString) {
    start = start.charCodeAt(0);
    stop = stop.charCodeAt(0);
  }

  return Array.from(
    { length: (stop - start) / step + 1 },
    (_, i) => start + i * step
  ).map((n) => (isString ? String.fromCharCode(n) : n));
};
Enter fullscreen mode Exit fullscreen mode

Examples

// Generate the alphabet using Array.from making use of it being ordered as a sequence
range('A', 'Z', 1);
// ["A", "B", "C", "D", "E",  ..., "X", "Y", "Z"]

// Generate a sequence of letters with a step of 5
range('D', 'X', 5);
// ["D", "I", "N", "S", "X"]
Enter fullscreen mode Exit fullscreen mode

Demo

As usual, I created a stackblitz project to play with this code.

Top comments (0)