Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Last active May 4, 2018
Embed
What would you like to do?
Javascript: range() and range2d()
// will print numbers from 0 to 19
for (const x of range(20)) {
console.info(x);
}
// will print
// 0 0
// 1 0
// 0 1
// 1 1
// 0 2
// 1 2
for (const [x, y] of range2d(2, 3)) {
console.info(x, y);
}
/**
* Iterates from begin to end. If just one value is provided, it is considered to be `end` and `begin` is set to zero.
* @param {Number} begin
* @param {Number} [end]
* @returns {IterableIterator<Number>}
*/
function *range(begin, end) {
if (arguments.length === 1) {
end = begin;
begin = 0;
}
let increment = begin < end ? 1 : -1;
for (let i = begin; increment > 0 ? i < end : i > end; i += increment) {
yield i;
}
}
/**
* Basically two nested range()s for looping through two variables at once.
*
* @param {Number} x0
* @param {Number} y0
* @param {Number} [x1]
* @param {Number} [y1]
* @returns {IterableIterator<[Number, Number]>}
*/
function *range2d(x0, y0, x1, y1) {
if (arguments.length === 2) {
x1 = x0;
y1 = y0;
x0 = y0 = 0;
}
for (const y of range(y0, y1)) {
for (const x of range(x0, x1)) {
yield [x, y];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment