99 * @see https://www.techiedelight.com/flood-fill-algorithm/
1010 */
1111
12- const neighbors = [
12+ const neighborOffsets = [
1313 [ - 1 , - 1 ] ,
1414 [ - 1 , 0 ] ,
1515 [ - 1 , 1 ] ,
@@ -32,6 +32,15 @@ function checkLocation(rgbData, location) {
3232 }
3333}
3434
35+ function * neighbors ( rgbData , location ) {
36+ for ( const offset of neighborOffsets ) {
37+ const neighborLocation = [ location [ 0 ] + offset [ 0 ] , location [ 1 ] + offset [ 1 ] ]
38+ if ( isInside ( rgbData , neighborLocation ) ) {
39+ yield neighborLocation
40+ }
41+ }
42+ }
43+
3544/**
3645 * Implements the flood fill algorithm through a breadth-first approach using a queue.
3746 *
@@ -96,13 +105,8 @@ function breadthFirstFill(
96105
97106 if ( rgbData [ currentLocation [ 0 ] ] [ currentLocation [ 1 ] ] === targetColor ) {
98107 rgbData [ currentLocation [ 0 ] ] [ currentLocation [ 1 ] ] = replacementColor
99-
100- for ( let i = 0 ; i < neighbors . length ; i ++ ) {
101- const x = currentLocation [ 0 ] + neighbors [ i ] [ 0 ]
102- const y = currentLocation [ 1 ] + neighbors [ i ] [ 1 ]
103- if ( x >= 0 && x < rgbData . length && y >= 0 && y < rgbData [ 0 ] . length ) {
104- queue . push ( [ x , y ] )
105- }
108+ for ( const neighborLocation of neighbors ( rgbData , currentLocation ) ) {
109+ queue . push ( neighborLocation )
106110 }
107111 }
108112}
@@ -118,15 +122,8 @@ function breadthFirstFill(
118122function depthFirstFill ( rgbData , location , targetColor , replacementColor ) {
119123 if ( rgbData [ location [ 0 ] ] [ location [ 1 ] ] === targetColor ) {
120124 rgbData [ location [ 0 ] ] [ location [ 1 ] ] = replacementColor
121-
122- for ( let i = 0 ; i < neighbors . length ; i ++ ) {
123- const newLocation = [
124- location [ 0 ] + neighbors [ i ] [ 0 ] ,
125- location [ 1 ] + neighbors [ i ] [ 1 ]
126- ]
127- if ( isInside ( rgbData , newLocation ) ) {
128- depthFirstFill ( rgbData , newLocation , targetColor , replacementColor )
129- }
125+ for ( const neighborLocation of neighbors ( rgbData , location ) ) {
126+ depthFirstFill ( rgbData , neighborLocation , targetColor , replacementColor )
130127 }
131128 }
132129}
0 commit comments