Browse Source

Move generation function to lib

master
Dylan Baker 3 years ago
parent
commit
b96d925de3
2 changed files with 28 additions and 27 deletions
  1. 3
    27
      src/Board.tsx
  2. 25
    0
      src/lib.ts

+ 3
- 27
src/Board.tsx View File

@@ -1,7 +1,7 @@
1 1
 import React from 'react';
2 2
 import Cell from './Cell';
3 3
 import Controls from './Controls';
4
-import { countLivingNeighbors } from './lib';
4
+import { generateNewGrid } from './lib';
5 5
 
6 6
 interface Props {
7 7
   width?: number;
@@ -32,32 +32,8 @@ class Board extends React.Component<Props, State> {
32 32
 
33 33
   start = () => {
34 34
     this.timer = setInterval(() => {
35
-      console.log('Iterating');
36
-      const { grid } = this.state;
37
-      const newGrid = [...grid].map((row, y) => {
38
-        const newRow = [...row].map((cell, x) => {
39
-          const isAlive = cell;
40
-          const livingNeighbors = countLivingNeighbors(grid, x, y);
41
-
42
-          if (isAlive) {
43
-            if (livingNeighbors === 2 || livingNeighbors === 3) {
44
-              return true;
45
-            } else {
46
-              return false;
47
-            }
48
-          } else {
49
-            if (livingNeighbors === 3) {
50
-              return true;
51
-            }
52
-          }
53
-
54
-          return isAlive;
55
-        });
56
-
57
-        return newRow;
58
-      });
59
-
60
-      this.setState({ grid: newGrid });
35
+      const grid = generateNewGrid(this.state.grid);
36
+      this.setState({ grid });
61 37
     }, this.state.speed);
62 38
   };
63 39
 

+ 25
- 0
src/lib.ts View File

@@ -1,3 +1,28 @@
1
+export const generateNewGrid = (grid: boolean[][]) => {
2
+  return [...grid].map((row, y) => {
3
+    const newRow = [...row].map((cell, x) => {
4
+      const isAlive = cell;
5
+      const livingNeighbors = countLivingNeighbors(grid, x, y);
6
+
7
+      if (isAlive) {
8
+        if (livingNeighbors === 2 || livingNeighbors === 3) {
9
+          return true;
10
+        } else {
11
+          return false;
12
+        }
13
+      } else {
14
+        if (livingNeighbors === 3) {
15
+          return true;
16
+        }
17
+      }
18
+
19
+      return isAlive;
20
+    });
21
+
22
+    return newRow;
23
+  });
24
+};
25
+
1 26
 export const countLivingNeighbors = (
2 27
   grid: boolean[][],
3 28
   x: number,

Loading…
Cancel
Save