Skip to content

Commit e2ed863

Browse files
committed
refactor: Improve search functions
1 parent eaa18be commit e2ed863

File tree

1 file changed

+24
-34
lines changed

1 file changed

+24
-34
lines changed

search.go

Lines changed: 24 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,20 @@
11
package Text
22

3-
// Returns all occurences of needle in haystack
3+
// Returns all occurrences of needle in haystack
44
func findAll(haystack []rune, needle string) []int {
5-
65
needleAsRunes := []rune(needle)
76
lenNeedle := len(needleAsRunes)
87

98
if len(haystack) == 0 || len(needle) == 0 || lenNeedle > len(haystack) {
109
return []int{}
1110
}
1211

13-
items := make([]int, 0, 8)
14-
15-
for i := 0; i < len(haystack); i++ {
16-
for j := 0; j < lenNeedle; j++ {
17-
if haystack[i+j] != needleAsRunes[j] {
18-
break
19-
}
12+
var items []int
2013

21-
if j == lenNeedle-1 {
22-
items = append(items, i)
23-
}
14+
limit := len(haystack) - lenNeedle
15+
for i := 0; i <= limit; i++ {
16+
if matchAt(haystack, needleAsRunes, i) {
17+
items = append(items, i)
2418
}
2519
}
2620

@@ -36,17 +30,10 @@ func findFirst(haystack []rune, needle string) int {
3630
return -1
3731
}
3832

39-
lenHaystack := len(haystack)
40-
41-
for i := 0; i <= lenHaystack-lenNeedle; i++ {
42-
for j := 0; j < lenNeedle; j++ {
43-
if haystack[i+j] != needleAsRunes[j] {
44-
break
45-
}
46-
47-
if j == lenNeedle-1 {
48-
return i
49-
}
33+
limit := len(haystack) - lenNeedle
34+
for i := 0; i <= limit; i++ {
35+
if matchAt(haystack, needleAsRunes, i) {
36+
return i
5037
}
5138
}
5239

@@ -62,19 +49,22 @@ func findLast(haystack []rune, needle string) int {
6249
return -1
6350
}
6451

65-
lenHaystack := len(haystack)
66-
67-
for i := lenHaystack - lenNeedle; i >= 0; i-- {
68-
for j := 0; j < lenNeedle; j++ {
69-
if haystack[i+j] != needleAsRunes[j] {
70-
break
71-
}
72-
73-
if j == lenNeedle-1 {
74-
return i
75-
}
52+
limit := len(haystack) - lenNeedle
53+
for i := limit; i >= 0; i-- {
54+
if matchAt(haystack, needleAsRunes, i) {
55+
return i
7656
}
7757
}
7858

7959
return -1
8060
}
61+
62+
// Checks if the needle matches within the haystack starting at a given position.
63+
func matchAt(haystack []rune, needle []rune, pos int) bool {
64+
for j := range needle {
65+
if haystack[pos+j] != needle[j] {
66+
return false
67+
}
68+
}
69+
return true
70+
}

0 commit comments

Comments
 (0)