Skip to content

Commit 5e5f6ab

Browse files
vhoenVincent Hoen
andauthored
adds a sliceutils method to flatten a slice of slice of type I to a single level slice of type I (#20)
Co-authored-by: Vincent Hoen <vincent.hoen@ext.groupepvcp.com>
1 parent 859ad10 commit 5e5f6ab

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

docs/sliceutils/flatten.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Flatten
2+
3+
`Flatten[I any](input [][]I) []I`
4+
5+
Flatten - receives a slice of slice of type I and flattens it to a slice of type I.
6+
7+
```go
8+
package main
9+
10+
import (
11+
"github.com/Goldziher/go-utils/sliceutils"
12+
)
13+
14+
func main() {
15+
items := [][]int{
16+
{1, 2, 3, 4},
17+
{5, 6},
18+
{7, 8},
19+
{9, 10, 11},
20+
}
21+
22+
flattened := sliceutils.Flatten(items) //[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
23+
}
24+
```

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ nav:
1616
- sliceutils/findIndexesOf.md
1717
- sliceutils/findLastIndex.md
1818
- sliceutils/findLastIndexOf.md
19+
- sliceutils/flatten.md
1920
- sliceutils/forEach.md
2021
- sliceutils/includes.md
2122
- sliceutils/insert.md

sliceutils/sliceutils.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,14 @@ func Pluck[I any, O any](input []I, getter func(I) *O) []O {
338338

339339
return output
340340
}
341+
342+
// Flatten - receives a slice of slice of type I and flattens it to a slice of type I.
343+
func Flatten[I any](input [][]I) []I {
344+
var output []I
345+
346+
ForEach(input, func(item []I, index int, slice [][]I) {
347+
output = append(output, item...)
348+
})
349+
350+
return output
351+
}

sliceutils/sliceutils_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,3 +267,16 @@ func TestPluck(t *testing.T) {
267267
return &item.Value
268268
}))
269269
}
270+
271+
func TestFlatten(t *testing.T) {
272+
items := [][]int{
273+
{1, 2, 3, 4},
274+
{5, 6},
275+
{7, 8},
276+
{9, 10, 11},
277+
}
278+
279+
flattened := sliceutils.Flatten(items)
280+
281+
assert.Equal(t, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, flattened)
282+
}

0 commit comments

Comments
 (0)