9
9
* @see https://www.techiedelight.com/flood-fill-algorithm/
10
10
*/
11
11
12
- const neighbors = [
12
+ const neighborOffsets = [
13
13
[ - 1 , - 1 ] ,
14
14
[ - 1 , 0 ] ,
15
15
[ - 1 , 1 ] ,
@@ -32,6 +32,15 @@ function checkLocation(rgbData, location) {
32
32
}
33
33
}
34
34
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
+
35
44
/**
36
45
* Implements the flood fill algorithm through a breadth-first approach using a queue.
37
46
*
@@ -96,13 +105,8 @@ function breadthFirstFill(
96
105
97
106
if ( rgbData [ currentLocation [ 0 ] ] [ currentLocation [ 1 ] ] === targetColor ) {
98
107
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 )
106
110
}
107
111
}
108
112
}
@@ -118,15 +122,8 @@ function breadthFirstFill(
118
122
function depthFirstFill ( rgbData , location , targetColor , replacementColor ) {
119
123
if ( rgbData [ location [ 0 ] ] [ location [ 1 ] ] === targetColor ) {
120
124
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 )
130
127
}
131
128
}
132
129
}
0 commit comments