DEV Community

Discussion on: Using Python range() in JavaScript

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