-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrid.js
57 lines (56 loc) · 1.56 KB
/
grid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Grid {
constructor(array){
this.width = Math.ceil(Math.sqrt(array.length));
this.length = Math.ceil(Math.sqrt(array.length));
this.rows = {};
this.setRowsFromArray(array);
}
setRowsFromArray(array){
let rowCounter = 0;
let arrayIndex = 0;
while(rowCounter < this.length){
let length = arrayIndex + this.length;
for(let i = arrayIndex; i < length; i++){
if(!this.rows[rowCounter]){
this.rows[rowCounter] = [];
}
this.rows[rowCounter].push(array[i]);
arrayIndex = i + 1;
}
rowCounter++;
}
}
setRow(index, row){
this.rows[index] = row;
}
getRow(index){
return this.rows[index];
}
getColumn(index){
let column = [];
Object.keys(this.rows).forEach(row => {
while(this.rows[row].length < this.length){
if(row % 2 == 0){
this.rows[row].push(undefined);
} else {
this.rows[row].unshift(undefined);
}
}
column.push(this.rows[row][index])
});
return column;
}
setRowsFromColumns(columns){
let rows = {};
for(let i=0; i< columns.length; i++){
if(!rows[i]){
rows[i] = [];
}
columns.forEach( column => {
rows[i].push(column[i])
});
}
this.rows = rows;
}
}
module.exports = Grid;