@@ -3,13 +3,13 @@ class Plants {
33 this . generations = [ ]
44 this . boundaryBuffers = [ 0 , 0 ]
55 this . rules = { }
6- this . _setInitialGeneration ( initial )
76 if ( rules && rules . length > 0 ) {
87 rules . forEach ( ( rule ) => {
98 this . addRule ( rule )
109 } )
1110 }
1211 this . boundaryBuffers = this . getBoundaryBuffers ( )
12+ this . _setInitialGeneration ( initial )
1313 }
1414
1515 _setInitialGeneration ( initial ) {
@@ -21,6 +21,7 @@ class Plants {
2121 }
2222 } )
2323 )
24+ this . generations [ 0 ] = this . pad ( this . generations [ 0 ] )
2425 }
2526
2627 /**
@@ -51,7 +52,7 @@ class Plants {
5152 const prevGen = this . generations [ this . generations . length - 1 ]
5253
5354 // 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 ) => {
5556 // Assemble pattern for the given pot
5657 let pattern = ''
5758 for ( let x = pot . position - 2 ; x <= pot . position + 2 ; x ++ ) {
@@ -66,15 +67,7 @@ class Plants {
6667 }
6768 } )
6869
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 )
7871
7972 // Store the new generation
8073 this . generations . push ( nextGen )
@@ -180,6 +173,23 @@ class Plants {
180173 return this . generations [ generation ] . filter ( ( p ) => p . state === '#' )
181174 . reduce ( ( pacc , p ) => pacc + p . position , 0 )
182175 }
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+ }
183193}
184194
185195module . exports = {
0 commit comments