class Matrix {
constructor(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
this.content[y * width + x] = element(x, y);
}
}
}
get(x, y) {
return this.content[y * this.width + x];
}
set(x, y, value) {
this.content[y * this.width + x] = value;
}
*[Symbol.iterator]() {
let i=0;
while (i < this.height*this.width) {
yield {
x : i%this.width,
y : Math.floor(i/this.width),
value : this.content[i]
}
i++;
}
}
}
const width = 3;
let matrix = new Matrix(width, width, (x, y) => `[${x},${y}]= ${y * width + x}`);
for (let {value,x,y} of matrix) {
console.log(x,y,value);
}
https://es6console.com/jppky2fw/
0 0 [0,0]= 0
1 0 [1,0]= 1
2 0 [2,0]= 2
0 1 [0,1]= 3
1 1 [1,1]= 4
2 1 [2,1]= 5
0 2 [0,2]= 6
1 2 [1,2]= 7
2 2 [2,2]= 8
Autre exemple : lien