JSFiddle - React, Tailwind, and code Playground
by Ilya
JavaScript
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;
}
}
class MatrixIterator {
constructor(matrix) {
this.x = 0;
this.y = 0;
this.matrix = matrix;
}
next() {
if (this.y == this.matrix.height) return {done: true};
let 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}
}
}
Matrix.prototype[Symbol.iterator] = function() {
return new MatrixIterator(this)
}
let matrix = new Matrix(2, 2, (x, y) => `Значение x - ${x}, y - ${y}`);
for (let {x, y, value} of matrix) {
console.log(x,y,value)
}
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) {
super.set(x, y, value);
if (x != y) {
super.set(y,x,value);
}
}
}
let matrix2 = new SymmetricMatrix(5, (x, y) => `Значение x - ${x}, y - ${y}`)
console.log(matrix2.get(2,3));
class Group {
// Your code here.
constructor() {
this.group = [];
}
add(val) {
if (this.group.indexOf(val) === -1) {
this.group.push(val)
}
}
delete(val) {
this.group.filter(el => el !== val)
}
has(val) {
if (!this.group.indexOf(val) === -1) {
return true
} else {
return false
}
}
static from (arr) {
for (const el of arr) {
this.add(el)
}
}
}
let group = Group.from([10, 20]);
console.log(group.has(10));
// →...