Skip to content

Instantly share code, notes, and snippets.

@gnclmorais
Last active August 29, 2017 15:25
Show Gist options
  • Save gnclmorais/6ed85c90fdfc025581154c1262960985 to your computer and use it in GitHub Desktop.
Save gnclmorais/6ed85c90fdfc025581154c1262960985 to your computer and use it in GitHub Desktop.
Iterate over a matrix in JavaScript, cell by cell
function* flatten(matrix) {
for (var i = 0; i < matrix.length; i += 1) {
let column = matrix[i];
if (!Array.isArray(column)) yield column;
for (var j = 0; j < column.length; j += 1) {
yield column[j];
}
}
}
const matrix = [
[1, 2],
[3, 4]
];
const walker = flatten(matrix);
console.log(walker.next().value); // 1
console.log(walker.next().value); // 2
console.log(walker.next().value); // 3
console.log(walker.next().value); // 4
console.log(walker.next().value); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment