Skip to content

Commit 3bff35c

Browse files
committed
exstrings: add LongestSequenceOfFunc
1 parent dcc7459 commit 3bff35c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

exstrings/stringutil.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ func ConstantTimeEqual(a, b string) bool {
3232
return subtle.ConstantTimeCompare(UnsafeBytes(a), UnsafeBytes(b)) == 1
3333
}
3434

35+
// LongestSequenceOf returns the length of the longest contiguous sequence of a single rune in a string.
3536
func LongestSequenceOf(a string, b rune) int {
3637
// IndexRune has some optimizations, so use it to find the starting point
3738
firstIndex := strings.IndexRune(a, b)
@@ -52,3 +53,24 @@ func LongestSequenceOf(a string, b rune) int {
5253
}
5354
return maxCount
5455
}
56+
57+
// LongestSequenceOfFunc returns the length of the longest contiguous sequence of runes in a string.
58+
//
59+
// If the provided function returns zero or higher, the return value is added to the current count.
60+
// If the return value is negative, the count is reset to zero.
61+
func LongestSequenceOfFunc(a string, fn func(b rune) int) int {
62+
count := 0
63+
maxCount := 0
64+
for _, r := range a {
65+
val := fn(r)
66+
if val < 0 {
67+
count = 0
68+
} else {
69+
count += val
70+
if count > maxCount {
71+
maxCount = count
72+
}
73+
}
74+
}
75+
return maxCount
76+
}

0 commit comments

Comments
 (0)