Skip to content

Commit 16d73a1

Browse files
committed
Add a Concat slice function.
This is a variadic wrapper around Flatten that allows callers to assemble one slice from many slices without first joining them into a slice-of-slices.
1 parent f3e6605 commit 16d73a1

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

slice.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee fun
261261
}
262262

263263
// Flatten returns a slice a single level deep.
264+
// See also: Concat
264265
// Play: https://go.dev/play/p/rbp9ORaMpjw
265266
func Flatten[T any, Slice ~[]T](collection []Slice) Slice {
266267
totalLen := 0
@@ -276,6 +277,12 @@ func Flatten[T any, Slice ~[]T](collection []Slice) Slice {
276277
return result
277278
}
278279

280+
// Concat assembles >=1 slice’s members into a single slice.
281+
// See also: Flatten, Union.
282+
func Concat[T any, Slice ~[]T](collections ...Slice) Slice {
283+
return Flatten(collections)
284+
}
285+
279286
// Interleave round-robin alternating input slices and sequentially appending value at index into result.
280287
// Play: https://go.dev/play/p/-RJkTLQEDVt
281288
func Interleave[T any, Slice ~[]T](collections ...Slice) Slice {

slice_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,20 @@ func TestFlatten(t *testing.T) {
357357
is.IsType(nonempty, allStrings, "type preserved")
358358
}
359359

360+
func TestConcat(t *testing.T) {
361+
t.Parallel()
362+
is := assert.New(t)
363+
364+
result1 := Concat([][]int{{0, 1}, {2, 3, 4, 5}}...)
365+
366+
is.Equal(result1, []int{0, 1, 2, 3, 4, 5})
367+
368+
type myStrings []string
369+
allStrings := myStrings{"", "foo", "bar"}
370+
nonempty := Concat([]myStrings{allStrings}...)
371+
is.IsType(nonempty, allStrings, "type preserved")
372+
}
373+
360374
func TestInterleave(t *testing.T) {
361375
t.Parallel()
362376
is := assert.New(t)

0 commit comments

Comments
 (0)