range
The range utility generates an array of numbers starting from a base value up to (but not including) an end value, using a specified step increment. It is highly versatile for creating numeric sequences, loops, or lookup tables.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
/**
* Creates an array of numbers progressing from start up to, but not including, end. A step is used to specify the difference between each number in the array.
*
* @example
* ```ts
* const start = 0;
* const stop = 10;
* const step = 2;
*
* range(start, stop, step) // [0, 2, 4, 6, 8];
* ```
*
* @param start - The start of the range.
* @param stop - The end of the range.
* @param step - The value to increment or decrement by.
*
* @returns The range of numbers.
*
* @throws {TypeError} If start, stop, or step are not finite numbers.
* @throws {Error} If step is 0 or if range exceeds maximum size.
*/
export function range(start: number, stop: number, step: number) {
assert(
Number.isFinite(start) && Number.isFinite(stop) && Number.isFinite(step),
'start, stop, and step must be finite numbers',
{ args: { start, step, stop }, type: TypeError },
);
assert(step !== 0, 'Step cannot be 0', { args: { step }, type: Error });
if (start === stop) {
return [];
}
const length = Math.max(0, Math.ceil((stop - start) / step + Number.EPSILON));
assert(length <= 10_000_000, 'Range exceeds maximum allowed size of 10,000,000', {
args: { length, start, step, stop },
type: Error,
});
return Array.from({ length }, (_, i) => start + i * step);
}Features
- Isomorphic: Works in both Browser and Node.js.
- Bi-directional: Easily generate both ascending and descending sequences.
- Customizable Step: Control the gap between numbers in the sequence.
- Type-safe: Properly typed for numeric inputs and array results.
API
ts
function range(start: number, end?: number, step?: number): number[];Parameters
start: The inclusive beginning of the sequence.end: The exclusive end of the sequence.step: Optional. The amount to increment/decrement by (defaults to1or-1based on the range direction).
Returns
- An array of numbers containing the generated sequence.
Examples
Basic Ascending Ranges
ts
import { range } from '@vielzeug/toolkit';
range(0, 5); // [0, 1, 2, 3, 4]
range(1, 10, 2); // [1, 3, 5, 7, 9]Descending Ranges
ts
import { range } from '@vielzeug/toolkit';
// Automatic step detection
range(5, 0); // [5, 4, 3, 2, 1]
// Explicit negative step
range(10, 0, -2); // [10, 8, 6, 4, 2]Advanced Usage (Loops)
ts
import { range, map } from '@vielzeug/toolkit';
// Create 5 localized dates
const dates = map(range(0, 5), (day) => {
const d = new Date();
d.setDate(d.getDate() + day);
return d;
});Implementation Notes
- Returns an empty array if
stepis0or if the range is logically impossible (e.g.,start < endwith a negative step). - Performance-optimized for large sequences.
- Throws
TypeErrorif non-numeric arguments are provided.