Browse Source

Allow decreasing grid dimensions

master
Dylan Baker 3 years ago
parent
commit
b04edb9e4f
2 changed files with 53 additions and 17 deletions
  1. 7
    17
      src/Board.tsx
  2. 46
    0
      src/lib.ts

+ 7
- 17
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 { generateNewGrid } from './lib';
4
+import { generateNewGrid, updateGridDimensions } from './lib';
5 5
 
6 6
 const DEFAULT_WIDTH = 20;
7 7
 const DEFAULT_HEIGHT = 10;
@@ -80,23 +80,13 @@ class Board extends React.Component<{}, State> {
80 80
       this.setState({ height: dimensions.height });
81 81
     }
82 82
 
83
-    const width = dimensions.width ?? this.state.width;
84
-    const height = dimensions.height ?? this.state.height;
85
-
86
-    const grid = [...this.state.grid];
87
-    while (grid.length < height) {
88
-      grid.push(Array(width).fill(false));
89
-    }
90
-
91
-    const newGrid = grid.map((row) => {
92
-      while (row.length < width) {
93
-        row.push(false);
94
-      }
95
-
96
-      return row;
97
-    });
83
+    const grid = updateGridDimensions(
84
+      { width: this.state.width, height: this.state.height },
85
+      dimensions,
86
+      this.state.grid,
87
+    );
98 88
 
99
-    this.setState({ grid: newGrid });
89
+    this.setState({ grid });
100 90
   };
101 91
 
102 92
   render() {

+ 46
- 0
src/lib.ts View File

@@ -62,3 +62,49 @@ export const getNeighbors = (
62 62
 
63 63
   return neighbors;
64 64
 };
65
+
66
+export const updateGridDimensions = (
67
+  oldDimensions: {
68
+    width: number;
69
+    height: number;
70
+  },
71
+  newDimensions: { width?: number; height?: number },
72
+  grid: boolean[][],
73
+): boolean[][] => {
74
+  const width = newDimensions.width ?? oldDimensions.width;
75
+  const height = newDimensions.height ?? oldDimensions.height;
76
+
77
+  grid = [...grid];
78
+
79
+  if (height > oldDimensions.height) {
80
+    while (grid.length < height) {
81
+      grid.push(Array(width).fill(false));
82
+    }
83
+  } else if (height < oldDimensions.height) {
84
+    while (grid.length > height) {
85
+      if (grid.length <= 1) break;
86
+      grid.pop();
87
+    }
88
+  }
89
+
90
+  if (width > oldDimensions.width) {
91
+    grid = grid.map((row) => {
92
+      while (row.length < width) {
93
+        row.push(false);
94
+      }
95
+
96
+      return row;
97
+    });
98
+  } else if (width < oldDimensions.width) {
99
+    grid = grid.map((row) => {
100
+      while (row.length > width) {
101
+        if (row.length <= 1) break;
102
+        row.pop();
103
+      }
104
+
105
+      return row;
106
+    });
107
+  }
108
+
109
+  return grid;
110
+};

Loading…
Cancel
Save