DEV Community

Pasquale Mangialavori
Pasquale Mangialavori

Posted on

5 3

Python-like range iterator in Javascript

For mocking some data for tests or fill some array with fake data or whatever, sometimes I miss the python range iterator in Javascript.

myList = [0,1,2,3]
for i in range(0, len(myList))
    print i
Enter fullscreen mode Exit fullscreen mode

With the not so new by now specific of Javascript we can "generate" our own iterators.

An implementation of range could be this one:

function range(start = 0, end, step = 1) {
  return {
    *[Symbol.iterator]() {
      let newStart = start,
        newEnd = end;
      if (end < start) {
        newStart = end;
        newEnd = start;
      }
      for (let i = newStart; i < newEnd; i += step) {
        yield i;
      }
    }
  };
}

// forward
for (let element of range(0, 10)) {
    console.log({ element });
}

// and backwards
for (let element of range(0, -10)) {
    console.log({ element });
}
Enter fullscreen mode Exit fullscreen mode

We can write an even simpler implementation just writing the generator function.

function* range(start = 0, end, step = 1) {
  let newStart = start,
    newEnd = end;
  if (end < start) {
    newStart = end;
    newEnd = start;
  }
  for (let i = newStart; i < newEnd; i += step) {
    yield i;
  }
}

// forward
for (let element of range(0, 10)) {
    console.log({ element });
}

// and backwards
for (let element of range(0, -10)) {
    console.log({ element });
}

Enter fullscreen mode Exit fullscreen mode

Of course you must use the new for-of in order to iterate over it.

Just remember that the function returns always an iterator under the hood. So we can always easily take the iterator in this way if needed.

const it = range(0, 5)[Symbol.iterator]();
console.log(it.next()) // { value: 0, done: false }
console.log(it.next()) // { value: 1, done: false }
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️