Javascript: range() and range2d()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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