Skip to content

Commit ecdcebb

Browse files
authored
Deduplicate further
1 parent 3cb9b97 commit ecdcebb

File tree

1 file changed

+14
-20
lines changed

1 file changed

+14
-20
lines changed

Diff for: Recursive/FloodFill.js

+14-20
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
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,16 +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 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)
109110
}
110111
}
111112
}
@@ -121,15 +122,8 @@ function breadthFirstFill(
121122
function depthFirstFill(rgbData, location, targetColor, replacementColor) {
122123
if (rgbData[location[0]][location[1]] === targetColor) {
123124
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)
133127
}
134128
}
135129
}

0 commit comments

Comments
 (0)