A range function.
Ranges are immutable. All operations excluding iterative methods operate in O(1) time and space.
deno add jsr:@alg/range
Other Install Options
npx jsr add @alg/range
bunx jsr add @alg/range
pnpm i jsr:@alg/range
yarn add jsr:@alg/range
vlt install jsr:@alg/range
Range implements most non-mutating array methods. A selection of methods is shown below. See the API docs for more.
import {range} from "@alg/range";
const r = range(5); // or new Range(5);
// Iterating and Indexing
console.log([...r]); // [0, 1, 2, 3, 4]
console.log(r.at(-2)); // 3
console.log(r[3]); // 3
// Iterative Methods
r.forEach((e) => console.log(e)); // 0 \ 1 \ 2 \ 3 \ 4
console.log(r.reduce((a, e) => a + e)); // 10
// Chopping and Slicing
console.log([...r.toReversed()]); // [4, 3, 2, 1, 0]
console.log([...r.slice(1, -1)]); // [1, 2, 3]
// start, stop, step parameters
console.log([...range(1, 5)]); // [1, 2, 3, 4]
console.log([...range(1, 5, 2)]); // [1, 3]
console.log([...range(5, 1, -2)]); // [5, 3]