Pagination controls need the page numbers 1 to 10. A calendar needs the hours 0 to 23, and a countdown needs 10 down to 1. A grid editor resets a row of cells to empty. These are small helpers that every codebase ends up writing: make a list of numbers, or overwrite part of an array with one value.
Write three functions in range.js: fill, which writes one value into a part of an existing array; range, which makes a list of numbers; and rangeRight, which makes the same list in reverse.
functionfill(array, value, start, end) // returns array itselffunctionrange(start, end, step) // returns a new array of numbersfunctionrangeRight(start, end, step) // returns a new array of numbers
fill changes array in place: indexes start up to, but not including, end get value. start defaults to 0, end to array.length.
range(end) counts from 0. range(start, end) counts from start. Neither includes end.
step is the distance between numbers. Without it, the step is 1, or -1 when end is below start.
rangeRight returns what range returns with the same arguments, last number first.
It fills from start up to, not including, end, and returns the same array.
A negative start or end counts from the end of the array (-1 is the last index).
Positions before the start or after the end of the array are clipped to it; when start is not below end, nothing changes.
Fractional positions are cut toward zero (1.7 is 1, -1.5 is -1).
It fills holes, and every filled slot gets the same value (the same object, not copies).
It does not use Array.prototype.fill.
range and rangeRight:
range(4) is [0, 1, 2, 3]; range(1, 5) is [1, 2, 3, 4]; range(0, 20, 5) is [0, 5, 10, 15].
Without a step, a range whose end is below its start counts down: range(-4) is [0, -1, -2, -3].
A step that points away from end, a step of 0, or start equal to end gives [].
Fractional steps give the right count and never include end, however small the step: range(0, 1, 0.1) has 10 numbers, never 11, and range(0.1, 0.4, 0.1) has 3 (the last one is about 0.3).
rangeRight gives the same numbers as range, in reverse.
Both handle 100,000 numbers quickly, and any finite start, end and step, even endpoints further apart than Number.MAX_VALUE (range(-Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE) is [-Number.MAX_VALUE, 0]). A range with more numbers than an array can hold (2 ** 32 - 1) throws a RangeError instead of looping forever.