feat: adding hassuffix + hasprefix (#680)

This commit is contained in:
Samuel Berthe
2025-09-24 23:18:51 +02:00
committed by GitHub
parent 41cbf0fd2b
commit 9a5336a8f9
3 changed files with 78 additions and 0 deletions

View File

@@ -227,6 +227,8 @@ Supported search helpers:
- [IndexOf](#indexof)
- [LastIndexOf](#lastindexof)
- [HasPrefix](#hasprefix)
- [HasSuffix](#hassuffix)
- [Find](#find)
- [FindIndexOf](#findindexof)
- [FindLastIndexOf](#findlastindexof)
@@ -2546,6 +2548,34 @@ notFound := lo.LastIndexOf([]int{0, 1, 2, 1, 2, 3}, 6)
// -1
```
### HasPrefix
Returns true if the collection has the prefix.
```go
ok := lo.HasPrefix([]int{1, 2, 3, 4}, []int{42})
// false
ok := lo.HasPrefix([]int{1, 2, 3, 4}, []int{1, 2})
// true
```
[[play](https://go.dev/play/p/SrljzVDpMQM)]
### HasSuffix
Returns true if the collection has the suffix.
```go
ok := lo.HasSuffix([]int{1, 2, 3, 4}, []int{42})
// false
ok := lo.HasSuffix([]int{1, 2, 3, 4}, []int{3, 4})
// true
```
[[play](https://go.dev/play/p/bJeLetQNAON)]
### Find
Searches for an element in a slice based on a predicate. Returns element and true if element was found.

32
find.go
View File

@@ -36,6 +36,38 @@ func LastIndexOf[T comparable](collection []T, element T) int {
return -1
}
// HasPrefix returns true if the collection has the prefix.
// Play: https://go.dev/play/p/SrljzVDpMQM
func HasPrefix[T comparable](collection []T, prefix []T) bool {
if len(collection) < len(prefix) {
return false
}
for i := range prefix {
if collection[i] != prefix[i] {
return false
}
}
return true
}
// HasSuffix returns true if the collection has the suffix.
// Play: https://go.dev/play/p/bJeLetQNAON
func HasSuffix[T comparable](collection []T, suffix []T) bool {
if len(collection) < len(suffix) {
return false
}
for i := range suffix {
if collection[len(collection)-len(suffix)+i] != suffix[i] {
return false
}
}
return true
}
// Find searches for an element in a slice based on a predicate. Returns element and true if element was found.
// Play: https://go.dev/play/p/Eo7W0lvKTky
func Find[T any](collection []T, predicate func(item T) bool) (T, bool) {

View File

@@ -30,6 +30,22 @@ func TestLastIndexOf(t *testing.T) {
is.Equal(-1, result2)
}
func TestHasPrefix(t *testing.T) {
t.Parallel()
is := assert.New(t)
is.True(HasPrefix([]int{1, 2, 3, 4}, []int{1, 2}))
is.False(HasPrefix([]int{1, 2, 3, 4}, []int{42}))
}
func TestHasSuffix(t *testing.T) {
t.Parallel()
is := assert.New(t)
is.True(HasSuffix([]int{1, 2, 3, 4}, []int{3, 4}))
is.False(HasSuffix([]int{1, 2, 3, 4}, []int{42}))
}
func TestFind(t *testing.T) {
t.Parallel()
is := assert.New(t)