Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

range

Generates an array of numbers from start to end (exclusive) with a given step.

TypeScript
Copied!
1/**
2 * Generates an array of numbers from start to end (exclusive) with a given step.
3 *
4 * @param start - Starting number.
5 * @param end - End number (exclusive).
6 * @param step - Step value (default is 1).
7 * @returns Array of numbers in the specified range.
8 */
9export function range(start: number, end: number, step: number = 1): number[] {
10  const result: number[] = [];
11
12  if (step === 0) throw new Error('Step cannot be 0');
13
14  const increasing = step > 0;
15  if ((increasing && start >= end) || (!increasing && start <= end)) {
16    return result;
17  }
18
19  for (let i = start; increasing ? i < end : i > end; i += step) {
20    result.push(i);
21  }
22
23  return result;
24}
  • Supports Both Ascending and Descending Sequences

    Works seamlessly for increasing and decreasing ranges depending on the step sign.

  • Custom Step Size

    Offers flexibility to define the interval between values, enabling granular control over sequence generation.

  • Safe Handling of Invalid Input

    Throws an explicit error when step is zero and returns an empty array for invalid ranges.

  • Pure and Predictable

    Deterministic output with no side effects, making it safe for use in functional pipelines or unit tests.

  • Minimal and Performant

    Straightforward loop logic ensures good performance even on large ranges.

Tests | Examples

TypeScript
Copied!
1test('range - basic increasing range', () => {
2  expect(range(0, 5)).toEqual([0, 1, 2, 3, 4]);
3});
4
5test('range - with step 2', () => {
6  expect(range(1, 6, 2)).toEqual([1, 3, 5]);
7});
8
9test('range - decreasing range with negative step', () => {
10  expect(range(5, 0, -1)).toEqual([5, 4, 3, 2, 1]);
11});
12
13test('range - empty when step direction is invalid', () => {
14  expect(range(5, 0)).toEqual([]);
15  expect(range(0, 5, -1)).toEqual([]);
16});
17
18test('range - step of zero throws error', () => {
19  expect(() => range(0, 5, 0)).toThrow('Step cannot be 0');
20});
21
22test('range - single element range', () => {
23  expect(range(3, 4)).toEqual([3]);
24});

Common Use Cases

  • Generating Index Arrays

    Create sequential IDs or index arrays for iteration, pagination, or batching logic.

  • Chart and Graph Axes

    Produce labeled axis ticks at custom intervals for data visualizations.

  • Simulation or Sampling

    Generate numeric samples for simulations, physics calculations, or signal processing.

  • Animation and Timing Control

    Create time steps, keyframes, or value sequences for animations.

  • Testing and Mock Data

    Generate predictable numeric data for test cases or mock datasets.

Codebase: Utilities -> Numbers -> range | Yevhen Klymentiev