Skip to content

Commit b61e9a8

Browse files
committed
Add sorted slice utility functions (Insert, Delete, Contains)
1 parent f02a359 commit b61e9a8

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ func main() {
118118
})
119119

120120
fmt.Println(si)
121+
121122
// [11, 13, 13]
122123
}
123124
```

slices/sort.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package slices
2+
3+
import (
4+
"cmp"
5+
"slices"
6+
)
7+
8+
// Insert inserts an element into a sorted slice.
9+
func Insert[S ~[]E, E cmp.Ordered](s S, e E, unique bool) S {
10+
i, found := slices.BinarySearch(s, e)
11+
if found && unique {
12+
return s
13+
}
14+
return slices.Insert(s, i, e)
15+
}
16+
17+
// Delete deletes an element from a sorted slice.
18+
func Delete[S ~[]E, E cmp.Ordered](s S, e E) S {
19+
i, found := slices.BinarySearch(s, e)
20+
if found {
21+
return slices.Delete(s, i, i+1)
22+
}
23+
24+
return s
25+
}
26+
27+
// Contains checks if a slice contains an element.
28+
func Contains[T cmp.Ordered](s []T, e T) bool {
29+
_, found := slices.BinarySearch(s, e)
30+
31+
return found
32+
}

0 commit comments

Comments
 (0)