Generalize BreakUp/RangByChunks functions
This commit is contained in:
@@ -54,3 +54,28 @@ func Move[T any](slice []T, srcIndex int, dstIndex int) []T {
|
||||
value := slice[srcIndex]
|
||||
return Insert(Remove(slice, srcIndex), value, dstIndex)
|
||||
}
|
||||
|
||||
func BreakUp[T any](items []T, chunkSize int) [][]T {
|
||||
numTracks := len(items)
|
||||
var chunks [][]T
|
||||
for i := 0; i < numTracks; i += chunkSize {
|
||||
end := i + chunkSize
|
||||
if end > numTracks {
|
||||
end = numTracks
|
||||
}
|
||||
|
||||
chunks = append(chunks, items[i:end])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
func RangeByChunks[T any](items []T, chunkSize int, cb func([]T) error) error {
|
||||
chunks := BreakUp(items, chunkSize)
|
||||
for _, chunk := range chunks {
|
||||
err := cb(chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -69,4 +69,25 @@ var _ = Describe("Slice Utils", func() {
|
||||
Expect(slice.Move([]string{"1", "2", "3"}, 1, 1)).To(ConsistOf("1", "2", "3"))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("BreakUp", func() {
|
||||
It("returns no chunks if slice is empty", func() {
|
||||
var s []string
|
||||
chunks := slice.BreakUp(s, 10)
|
||||
Expect(chunks).To(HaveLen(0))
|
||||
})
|
||||
It("returns the slice in one chunk if len < chunkSize", func() {
|
||||
s := []string{"a", "b", "c"}
|
||||
chunks := slice.BreakUp(s, 10)
|
||||
Expect(chunks).To(HaveLen(1))
|
||||
Expect(chunks[0]).To(ConsistOf("a", "b", "c"))
|
||||
})
|
||||
It("breaks up the slice if len > chunkSize", func() {
|
||||
s := []string{"a", "b", "c", "d", "e"}
|
||||
chunks := slice.BreakUp(s, 3)
|
||||
Expect(chunks).To(HaveLen(2))
|
||||
Expect(chunks[0]).To(ConsistOf("a", "b", "c"))
|
||||
Expect(chunks[1]).To(ConsistOf("d", "e"))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user