-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.js
More file actions
68 lines (57 loc) · 1.82 KB
/
grid.js
File metadata and controls
68 lines (57 loc) · 1.82 KB
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
58
59
60
61
62
63
64
65
66
67
68
export function Grid({ rows, columns, defaultValue = "", wrap = false }) {
this.grid = init2dArray(rows, columns, defaultValue);
this.wrap = wrap;
}
function init2dArray(rows, cols, val = "") {
return new Array(rows).fill(null).map(() =>
new Array(cols).fill(null).map(() => {
return val;
})
);
}
Grid.prototype.get = function (row, col) {
return this.grid[row][col];
};
Grid.prototype.set = function (row, col, val) {
return (this.grid[row][col] = val);
};
Grid.prototype.up = function (row, col, val) {
const r = this.wrap
? (row - 1 + this.grid.length) % this.grid.length
: Math.max(row - 1, 0);
if (typeof val !== "undefined") this.grid[r][col] = val;
return this.grid[r][col];
};
Grid.prototype.down = function (row, col, val) {
const r = this.wrap
? (row + 1 + this.grid.length) % this.grid.length
: Math.min(row + 1, this.grid.length - 1);
if (typeof val !== "undefined") this.grid[r][col] = val;
return this.grid[r][col];
};
Grid.prototype.left = function (row, col, val) {
const c = this.wrap
? (col - 1 + this.grid[0].length) % this.grid[0].length
: Math.max(col - 1, 0);
if (typeof val !== "undefined") this.grid[row][c] = val;
return this.grid[row][c];
};
Grid.prototype.right = function (row, col, val) {
const c = this.wrap
? (col + 1 + this.grid[0].length) % this.grid[0].length
: Math.min(col + 1, this.grid[0].length - 1);
if (typeof val !== "undefined") this.grid[row][c] = val;
return this.grid[row][c];
};
Grid.prototype.north = function (row, col, val) {
return this.up(row, col, val);
};
Grid.prototype.south = function (row, col, val) {
return this.down(row, col, val);
};
Grid.prototype.west = function (row, col, val) {
return this.left(row, col, val);
};
Grid.prototype.east = function (row, col, val) {
return this.right(row, col, val);
};