Skip to content

Instantly share code, notes, and snippets.

@imfeng
Last active August 26, 2022 19:30
Show Gist options
  • Save imfeng/a47de31517d56f78c2282e5b56b283c0 to your computer and use it in GitHub Desktop.
Save imfeng/a47de31517d56f78c2282e5b56b283c0 to your computer and use it in GitHub Desktop.
const rows = 3;
const columns = 2;
console.log('1. Recursive version');
recusive2DArray(rows, columns, (i, j) => console.log(i, j));
console.log('2. While loop version');
while2DArray(rows, columns, (i, j) => console.log(i, j));
console.log('3. For loop version');
forloop2DArray(rows, columns, (i, j) => console.log(i, j));
console.log('4. yield version');
for(let [i, j] of twoDGenerator(rows, columns)) {
console.log(i, j);
}
function recusive2DArray(rows, cols, func, i = 0, j = 0) {
func(i, j);
if(j + 1 < cols) {
return recusive2DArray(rows, cols, func, i, j + 1);
}
if(i + 1 < rows) {
return recusive2DArray(rows, cols, func, i + 1, 0);
}
}
function while2DArray(rows, cols, func) {
let count = rows * cols;
while(count--) {
const i = Math.floor(count / cols);
const j = count % cols;
func(i, j);
}
}
function forloop2DArray(rows, cols, func) {
for(let i = 0; i < rows; i++) {
for(let j = 0; j < cols; j++) {
func(i, j);
}
}
}
function *twoDGenerator(rows, cols, i=0, j=0) {
j >= cols
? ((i + 1 >= rows) ? 0 : yield *twoDGenerator(rows, cols, i + 1, 0))
: ((yield [i, j]) || (yield *twoDGenerator(rows, cols, i, j + 1)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment