Skip to content

refactor: reduce code duplication in FloodFill #1645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions Recursive/FloodFill.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ const neighbors = [
[1, 1]
]

function checkLocation(rgbData, location) {
if (
location[0] < 0 ||
location[0] >= rgbData.length ||
location[1] < 0 ||
location[1] >= rgbData[0].length
) {
throw new Error('location should point to a pixel within the rgbData')
}
}

/**
* Implements the flood fill algorithm through a breadth-first approach using a queue.
*
Expand All @@ -34,14 +45,7 @@ export function breadthFirstSearch(
targetColor,
replacementColor
) {
if (
location[0] < 0 ||
location[0] >= rgbData.length ||
location[1] < 0 ||
location[1] >= rgbData[0].length
) {
throw new Error('location should point to a pixel within the rgbData')
}
checkLocation(rgbData, location)

const queue = []
queue.push(location)
Expand All @@ -65,14 +69,7 @@ export function depthFirstSearch(
targetColor,
replacementColor
) {
if (
location[0] < 0 ||
location[0] >= rgbData.length ||
location[1] < 0 ||
location[1] >= rgbData[0].length
) {
throw new Error('location should point to a pixel within the rgbData')
}
checkLocation(rgbData, location)

depthFirstFill(rgbData, location, targetColor, replacementColor)
}
Expand Down
13 changes: 13 additions & 0 deletions Recursive/test/FloodFill.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ describe('FloodFill', () => {
})
})

describe.each([breadthFirstSearch, depthFirstSearch])('%o', (floodFillFun) => {
it.each([
[1, -1],
[-1, 1],
[0, 7],
[7, 0]
])('throws for start position [%i, %i]', (location) => {
expect(() =>
floodFillFun(generateTestRgbData(), location, green, orange)
).toThrowError()
})
})

/**
* Utility-function to test the function "breadthFirstSearch".
*
Expand Down
Loading