Skip to content

Commit e6483bc

Browse files
committed
add safe slice
1 parent 90649fd commit e6483bc

File tree

2 files changed

+34
-11
lines changed

2 files changed

+34
-11
lines changed

slices/slices.go

+16-10
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,16 @@ func Intersect[T comparable](s []T, others ...[]T) []T {
109109
return result
110110
}
111111

112+
// SafeSlice
113+
// returns slice of slice via copy
114+
func SafeSlice[T any](s []T, from, to int) []T {
115+
if to > len(s) {
116+
to = len(s)
117+
}
118+
119+
return Copy(s[from:to])
120+
}
121+
112122
// Split
113123
// splits a given slice into parts by `partSize` elements
114124
func Split[T any](s []T, partSize int) [][]T {
@@ -117,19 +127,15 @@ func Split[T any](s []T, partSize int) [][]T {
117127
}
118128

119129
if len(s) <= partSize {
120-
return [][]T{s}
130+
return [][]T{SafeSlice(s, 0, len(s))}
121131
}
122132

123-
count := int(math.Ceil(float64(len(s)) / float64(partSize)))
124-
result := make([][]T, count)
133+
length := int(math.Ceil(float64(len(s)) / float64(partSize)))
125134

126-
for i := 0; i < count; i++ {
127-
from := partSize * i
128-
to := from + partSize
129-
if to > len(s) {
130-
to = len(s)
131-
}
132-
result[i] = s[from:to]
135+
result := make([][]T, length)
136+
137+
for i := 0; i < length; i++ {
138+
result[i] = SafeSlice(s, i*partSize, (i+1)*partSize)
133139
}
134140

135141
return result

slices/slices_test.go

+18-1
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,18 @@ func TestIntersect(t *testing.T) {
170170
}
171171
}
172172

173+
func TestSafeSlice(t *testing.T) {
174+
arr := Copy(stringSlice)
175+
176+
r := SafeSlice(arr, 1, 3)
177+
178+
arr[1] = "new"
179+
180+
if r[0] != "two" {
181+
t.Errorf(errorFormat, r, []string{"two", "three"})
182+
}
183+
}
184+
173185
func TestSplit(t *testing.T) {
174186
tests := []struct {
175187
name string
@@ -382,7 +394,12 @@ func TestFormat(t *testing.T) {
382394
exp []string
383395
}{
384396
{name: "empty", input: []float64{}, exp: []string{}},
385-
{name: "123", input: []float64{0.000001, 0.02, 0.300000003}, format: "%.2f", exp: []string{"0.00", "0.02", "0.30"}},
397+
{
398+
name: "123",
399+
input: []float64{0.000001, 0.02, 0.300000003},
400+
format: "%.2f",
401+
exp: []string{"0.00", "0.02", "0.30"},
402+
},
386403
}
387404
for _, tt := range tests {
388405
t.Run(tt.name, func(t *testing.T) {

0 commit comments

Comments
 (0)