Handle single word and empty string in lastWord() closes #4787 (#4891)

* Add test for #4787: lastWord() panics on single word or empty string

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix #4787: Handle single word and empty string in lastWord()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Nathan Wallace
2025-11-16 00:10:06 +08:00
committed by GitHub
parent 11ce53cfc4
commit f799be5447
2 changed files with 17 additions and 2 deletions

View File

@@ -73,7 +73,11 @@ func isFirstWord(text string) bool {
// split the string by spaces and return the last segment
func lastWord(text string) string {
return text[strings.LastIndex(text, " "):]
idx := strings.LastIndex(text, " ")
if idx == -1 {
return text
}
return text[idx:]
}
//

View File

@@ -64,7 +64,8 @@ func TestIsFirstWord(t *testing.T) {
}
}
// TestLastWord tests the lastWord helper function (only passing cases)
// TestLastWord tests the lastWord helper function
// Bug: #4787 - lastWord() panics on single word or empty string
func TestLastWord(t *testing.T) {
tests := []struct {
name string
@@ -96,6 +97,16 @@ func TestLastWord(t *testing.T) {
input: "select 🔥",
expected: " 🔥",
},
{
name: "single_word", // #4787
input: "select",
expected: "select",
},
{
name: "empty_string", // #4787
input: "",
expected: "",
},
}
for _, tt := range tests {