Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Last active May 4, 2018 01:39
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 luciopaiva/9415fa01f61e3221ca7e1fd20eca043d to your computer and use it in GitHub Desktop.
Save luciopaiva/9415fa01f61e3221ca7e1fd20eca043d to your computer and use it in GitHub Desktop.
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