MCPcopy Create free account
hub / github.com/MultithreadedJSBook/code-samples / Grid

Class Grid

ch5-game-of-life/thread-gol.js:1–43  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Grid {
2 constructor(size, buffer, paint = () => {}) {
3 const sizeSquared = size * size;
4 this.buffer = buffer;
5 this.size = size;
6 this.cells = new Uint8Array(this.buffer, 0, sizeSquared);
7 this.nextCells = new Uint8Array(this.buffer, sizeSquared, sizeSquared);
8 this.paint = paint;
9 }
10
11 getCell(x, y) {
12 const size = this.size;
13 const sizeM1 = size - 1;
14 x = x < 0 ? sizeM1 : x > sizeM1 ? 0 : x;
15 y = y < 0 ? sizeM1 : y > sizeM1 ? 0 : y;
16 return this.cells[size * x + y];
17 }
18
19 static NEIGHBORS = [
20 [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]
21 ];
22
23 iterate(minX, minY, maxX, maxY) {
24 const size = this.size;
25
26 for (let x = minX; x < maxX; x++) {
27 for (let y = minY; y < maxY; y++) {
28 const cell = this.cells[size * x + y];
29 let alive = 0;
30 for (const [i, j] of Grid.NEIGHBORS) {
31 alive += this.getCell(x + i, y + j);
32 }
33 const newCell = alive === 3 || (cell && alive === 2) ? 1 : 0;
34 this.nextCells[size * x + y] = newCell;
35 this.paint(newCell, x, y);
36 }
37 }
38
39 const cells = this.nextCells;
40 this.nextCells = this.cells;
41 this.cells = cells;
42 }
43}
44
45const BLACK = 0xFF000000;
46const WHITE = 0xFFFFFFFF;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected