DEV Community

Discussion on: Using Python range() in JavaScript

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Your code is really weird you mix iterator protocol with generators. You just can use this, it will do the same:

function* range(start, stop) {
    if (stop === undefined) {
        stop = start
        start = 0
    }
    for (let n = start; n < stop; ++n) yield n;
}
Enter fullscreen mode Exit fullscreen mode

I've also written an article on higer order iterators including async but in Polish (you can use translate option to read it).

Generatory i Iteratory wyższego poziomu

Collapse
 
lionelrowe profile image
lionel-rowe

Not weird at all, it's a common pattern. That way, you can easily extend your range objects with other properties, like min, max, includes, etc.

More importantly, it also ensures you don't accidentally mutate the range and get unexpected results. With your version:

const r = range(1, 10)
;[...r] // [1, 2, 3, 4, 5, 6, 7, 8, 9], as expected
;[...r] // [], empty array, because the iterator has already been consumed
Enter fullscreen mode Exit fullscreen mode

With my version:

const r = range(1, 10)
;[...r] // [1, 2, 3, 4, 5, 6, 7, 8, 9], as expected
;[...r] // [1, 2, 3, 4, 5, 6, 7, 8, 9], same as before
Enter fullscreen mode Exit fullscreen mode

You can still get a mutable iterator from my version if you really need one, though. You just have to ask for it explicitly:

const i = range(1, 10)[Symbol.iterator]()
;[...i] // [1, 2, 3, 4, 5, 6, 7, 8, 9]
;[...i] // []
Enter fullscreen mode Exit fullscreen mode