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,16 +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 newLocation = [
102
- currentLocation [ 0 ] + neighbors [ i ] [ 0 ] ,
103
- currentLocation [ 1 ] + neighbors [ i ] [ 1 ]
104
- ]
105
- isInside ( rgbData , newLocation )
106
- if ( isInside ( rgbData , newLocation ) ) {
107
- queue . push ( newLocation )
108
- }
108
+ for ( const neighborLocation of neighbors ( currentLocation ) ) {
109
+ queue . push ( neighborLocation )
109
110
}
110
111
}
111
112
}
@@ -121,15 +122,8 @@ function breadthFirstFill(
121
122
function depthFirstFill ( rgbData , location , targetColor , replacementColor ) {
122
123
if ( rgbData [ location [ 0 ] ] [ location [ 1 ] ] === targetColor ) {
123
124
rgbData [ location [ 0 ] ] [ location [ 1 ] ] = replacementColor
124
-
125
- for ( let i = 0 ; i < neighbors . length ; i ++ ) {
126
- const newLocation = [
127
- location [ 0 ] + neighbors [ i ] [ 0 ] ,
128
- location [ 1 ] + neighbors [ i ] [ 1 ]
129
- ]
130
- if ( isInside ( rgbData , newLocation ) ) {
131
- depthFirstFill ( rgbData , newLocation , targetColor , replacementColor )
132
- }
125
+ for ( const neighborLocation of neighbors ( currentLocation ) ) {
126
+ depthFirstFill ( rgbData , neighborLocation , targetColor , replacementColor )
133
127
}
134
128
}
135
129
}
0 commit comments