Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active January 4, 2023 20:14
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 crazy4groovy/4d871aadad1d71754a863e92f119c489 to your computer and use it in GitHub Desktop.
Save crazy4groovy/4d871aadad1d71754a863e92f119c489 to your computer and use it in GitHub Desktop.
Generator function to iterate over a set of numbers, or create an array of numbers; matches python's native `range` and `list` functions (JavaScript) (Deno)
// ES Module: import { range, list } from 'https://gist.githubusercontent.com/crazy4groovy/4d871aadad1d71754a863e92f119c489/raw/range-list.js'
// function range(begin: number?, end: number?, inc: number?) => Generator<number>
export function* range(b = 0, e, i = 1) {
if (e === undefined) {
// shift args
e = b;
b = 0;
}
// handle -ve inc
let checkDiff = (b, e) => (b < e);
if (i < 0) checkDiff = (b, e) => (b > e);
while (checkDiff(b, e)) {
yield b;
b += i;
}
return e;
}
/// for (let i of range(3)) console.log(i); // 0\n1\n2\n
/// for (let i of range(2, 5)) console.log(i); // 2\n3\n4\n
/// for (let i of range(2, 6, 3)) console.log(i); // 2\n5\n
/// for (let i of range(2, 5, 3)) console.log(i); // 2\n
/// for (let i of range(9, 0, -2)) console.log(i); // 9\n7\n5\n3\n1\n
// function list(gen: Generator<T>) => T[]
export function list(gen) {
const arr = [];
for (let r of gen) arr.push(r);
return arr;
}
/// console.log(list(range(3))); // [0, 1, 2]
/// console.log(list(range(2, 5))); // [2, 3, 4]
/// console.log(list(range(2, 6, 3))); // [2, 5]
/// console.log(list(range(2, 5, 3))); // [2]
/* Convenience methods only: */
list.range = (...args) => list(range(...args));
range.list = list.range;
/// console.log(list.range(2, 6, 3)); // [2, 5]
/// console.log(range.list(2, 6, 3)); // [2, 5]
/* Hacks/shortcuts */
export const listRange = (begin, end, inc = 1) =>
Array.from({ length: ((end - begin) / inc) + 1 }, (_, i) => begin + i * inc);
// console.log(listRange(0, 4, 1)); // [0, 1, 2, 3, 4]
// console.log(listRange(0, 4)); // [0, 1, 2, 3, 4]
// console.log(listRange(1, 10, 2)); // [1, 3, 5, 7, 9]
const listRange = (begin, end, inc = 1) =>
Array.from({ length: Math.ceil((end - begin) / inc) }, (_, i) => begin + i * inc);
// console.log(listRange(0, 4, 1)); // [0, 1, 2, 3]
// console.log(listRange(0, 4)); // [0, 1, 2, 3]
// console.log(listRange(1, 10, 2)); // [1, 3, 5, 7, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment