@@ -3,13 +3,13 @@ class Plants {
3
3
this . generations = [ ]
4
4
this . boundaryBuffers = [ 0 , 0 ]
5
5
this . rules = { }
6
- this . _setInitialGeneration ( initial )
7
6
if ( rules && rules . length > 0 ) {
8
7
rules . forEach ( ( rule ) => {
9
8
this . addRule ( rule )
10
9
} )
11
10
}
12
11
this . boundaryBuffers = this . getBoundaryBuffers ( )
12
+ this . _setInitialGeneration ( initial )
13
13
}
14
14
15
15
_setInitialGeneration ( initial ) {
@@ -21,6 +21,7 @@ class Plants {
21
21
}
22
22
} )
23
23
)
24
+ this . generations [ 0 ] = this . pad ( this . generations [ 0 ] )
24
25
}
25
26
26
27
/**
@@ -51,7 +52,7 @@ class Plants {
51
52
const prevGen = this . generations [ this . generations . length - 1 ]
52
53
53
54
// Loop through all pots in the last generation to create a new generation
54
- const nextGen = prevGen . map ( ( pot ) => {
55
+ let nextGen = prevGen . map ( ( pot ) => {
55
56
// Assemble pattern for the given pot
56
57
let pattern = ''
57
58
for ( let x = pot . position - 2 ; x <= pot . position + 2 ; x ++ ) {
@@ -66,15 +67,7 @@ class Plants {
66
67
}
67
68
} )
68
69
69
- // Padd the list to support future generation
70
- for ( let x = 1 ; x <= this . boundaryBuffers [ 0 ] ; x ++ ) {
71
- const first = nextGen [ 0 ] . position
72
- nextGen . splice ( 0 , 0 , { position : first - 1 , state : '.' } )
73
- }
74
- for ( let x = 1 ; x <= this . boundaryBuffers [ 1 ] ; x ++ ) {
75
- const last = nextGen [ nextGen . length - 1 ] . position
76
- nextGen . push ( { position : last + 1 , state : '.' } )
77
- }
70
+ nextGen = this . pad ( nextGen )
78
71
79
72
// Store the new generation
80
73
this . generations . push ( nextGen )
@@ -180,6 +173,23 @@ class Plants {
180
173
return this . generations [ generation ] . filter ( ( p ) => p . state === '#' )
181
174
. reduce ( ( pacc , p ) => pacc + p . position , 0 )
182
175
}
176
+
177
+ /**
178
+ * Pads the generation to the left and right so the pots are present to support future generations
179
+ * @param {Array } generation List of pots representing a generation
180
+ * @returns generation list with extra pots
181
+ */
182
+ pad ( generation ) {
183
+ for ( let x = 1 ; x <= this . boundaryBuffers [ 0 ] ; x ++ ) {
184
+ const first = generation [ 0 ] . position
185
+ generation . splice ( 0 , 0 , { position : first - 1 , state : '.' } )
186
+ }
187
+ for ( let x = 1 ; x <= this . boundaryBuffers [ 1 ] ; x ++ ) {
188
+ const last = generation [ generation . length - 1 ] . position
189
+ generation . push ( { position : last + 1 , state : '.' } )
190
+ }
191
+ return generation
192
+ }
183
193
}
184
194
185
195
module . exports = {
0 commit comments