Skip to content

Instantly share code, notes, and snippets.

@mogeko
Last active October 31, 2022 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mogeko/cebc85d49a976e380a61535898e84e1a to your computer and use it in GitHub Desktop.
Save mogeko/cebc85d49a976e380a61535898e84e1a to your computer and use it in GitHub Desktop.
This function returns a sequence of numbers.
/**
* This function returns a sequence of numbers.
*
* @param length - The length of the array to create
* @returns An array of numbers from 0 to `length` - 1
*
* @example
* ```typescript
* range(0); // []
* range(5); // [0, 1, 2, 3, 4]
* ```
*/
export function range(length: number): number[];
/**
*
* This function returns a sequence of numbers.
*
* @param start - The start of the sequence (included)
* @param stop - The end of the sequence (not included)
* @returns an array of sequential numbers between `start` and `stop`
*
* @example
* ```typescript
* range(1, 5); // [1, 2, 3, 4]
* ```
*/
export function range(start: number, stop?: number): number[];
/**
* This function returns a sequence of numbers.
*
* @param start - The start of the sequence (included)
* @param stop - The end of the sequence (not included)
* @param step - The step between each number
* @returns an array of sequential numbers between `start`
* and `stop`, incremented by `step`
*
* @example
* ```typescript
* range(1, 6, 2); // [1, 3, 5]
* ```
*/
export function range(start: number, stop?: number, step?: number): number[];
export function range(start: number, stop?: number, step?: number) {
const [_start, _stop, _step] = stop
? [start, stop, step ?? 1]
: [0, start, 1];
const length = Math.max(Math.ceil((_stop - _start) / _step), 0);
return Array.from({ length }, (_, i) => _start + i * _step);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment