The original code was deeply nested within the handleKeyDown function, leading to several layers of nested if conditions and complex logic within a single function.
Before:
The logic for handling suggestions was all inside the handleKeyDown function, which led to deep nesting.
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setShowSuggestions(false)
inputRef.current?.blur()
} else if (event.key === 'Enter' && highlightedIndex !== null) {
const { index, subIndex } = highlightedIndex
const suggestion = suggestions[index].hits[subIndex]
handleSuggestionClick(suggestion as Chapter | Organization | Project | User | Event)
}
}
After:
The logic is broken down into smaller, reusable functions that perform specific tasks. For example, closeSuggestions handles the logic for closing suggestions and blurring the input, and moveHighlightDown handles the logic for moving the highlighted suggestion down.
const closeSuggestions = () => {
setShowSuggestions(false)
inputRef.current?.blur()
}
const selectHighlightedSuggestion = () => {
if (highlightedIndex === null) return
const { index, subIndex } = highlightedIndex
const suggestion = suggestions[index].hits[subIndex]
handleSuggestionClick(suggestion as Chapter | Organization | Project | User | Event)
}
By extracting the logic into separate functions, the overall code complexity is reduced and more readable.
In each extracted function (e.g., selectHighlightedSuggestion), early returns are used to avoid deep nesting:
const selectHighlightedSuggestion = () => {
if (highlightedIndex === null) return
const { index, subIndex } = highlightedIndex
const suggestion = suggestions[index].hits[subIndex]
handleSuggestionClick(suggestion as Chapter | Organization | Project | User | Event)
}
This pattern helps avoid deeply nested conditions, which makes the logic clearer and easier to maintain.