Last active
August 29, 2017 15:25
-
-
Save gnclmorais/6ed85c90fdfc025581154c1262960985 to your computer and use it in GitHub Desktop.
Iterate over a matrix in JavaScript, cell by cell
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
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]; | |
} | |
} | |
} |
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
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