this function is the iterator version of rangeArray, mimicking python's range function.

you can iterate indefinitely with this function if you set the end parameter to undefined, and then define the direction of the step increments with the step parameter. (a negative step will result in a decreasing sequence of numbers).

a number in the sequence of the given range.

import { assertEquals } from "jsr:@std/assert"

// aliasing our functions for brevity
const
fn = rangeIterator,
eq = assertEquals

eq([...fn(0, 5)], [0, 1, 2, 3, 4])
eq([...fn(-2, 3)], [-2, -1, 0, 1, 2])
eq([...fn(2, 7)], [2, 3, 4, 5, 6])
eq([...fn(2, 7.1)], [2, 3, 4, 5, 6, 7])
eq([...fn(0, 1, 0.2)], [0, 0.2, 0.4, 0.6, 0.8])
eq([...fn(1, -1, 0.4)], [1, 0.6, 0.2, -0.2, -0.6])
eq([...fn(1, -1, -0.4)], [1, 0.6, 0.2, -0.2, -0.6])

// indefinite sequence in the positive direction
const
loop_limit = 10,
accumulation_arr: number[] = []
for (const v of fn(0)) {
if (v >= loop_limit) { break }
accumulation_arr.push(v)
}
eq(accumulation_arr, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
accumulation_arr.splice(0) // clearing our array for the next test

// indefinite sequence in the negative direction
for (const v of fn(0, undefined, -1)) {
if (v <= -loop_limit) { break }
accumulation_arr.push(v)
}
eq(accumulation_arr, [0, -1, -2, -3, -4, -5, -6, -7, -8, -9])
  • Parameters

    • start: number = 0

      the initial number to begin the output range sequence from. defaults to 0.

    • Optionalend: number

      the final exclusive number to end the output range sequence at. its value will not be in the last output number. if left undefined, then it will be assumed to be Number.POSITIVE_INFINITY if step is a positive number (default), or it will become Number.NEGATIVE_INFINITY if step is a negative number. defaults to undefined.

    • step: number = 1

      a number, dictating how large each step from the start to the end should be. defaults to 1.

    • decimal_precision: number = 6

      an integer that specifies the number of decimal places to which the output numbers should be rounded to, in order to nullify floating point arithmetic inaccuracy. defaults to 6 (6 decimal places; i.e. rounds to the closest micro-number (10**(-6))).

    Returns IterableIterator<number, number>

    the total number of elements that were outputted.