Created
October 16, 2018 14:25
-
-
Save zhjgithub/0872c0664cf3a129655c4e0a228e48f3 to your computer and use it in GitHub Desktop.
matrix, iterator and symmetric matrix
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
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]() { | |
return new MatrixIterator(this) | |
} | |
} | |
class SymmetricMatrix extends Matrix { | |
constructor(size, element = (x,y) => undefined) { | |
super(size, size, (x,y) => { | |
if(x < y) return element(y,x) | |
else return element(x,y) | |
}) | |
} | |
set(x, y, value) { | |
super.set(x, y, value) | |
if(x !== y) super.set(y, x, value) | |
} | |
} | |
class MatrixIterator { | |
constructor(matrix) { | |
this.x = 0; | |
this.y = 0; | |
this.matrix = matrix; | |
} | |
next(){ | |
if(this.y === this.matrix.height) return {done: true} | |
const value = { | |
x: this.x, | |
y: this.y, | |
value: this.matrix.get(this.x, this.y) | |
} | |
this.x++; | |
if(this.x === this.matrix.width) { | |
this.x = 0; | |
this.y++ | |
} | |
return {value, done: false} | |
} | |
} | |
const matrix = new Matrix(2,2, (x,y)=>`value: (${x}, ${y})`); | |
for(let {x,y,value} of matrix){ | |
console.log(x, y, value) | |
} | |
const symmetricMatrix = new SymmetricMatrix(5, (x,y)=>`value: (${x}, ${y})`); | |
console.log(symmetricMatrix.get(2, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment