SPAN Digital Slices
Generic functions which operate on Go slices.
Filter a slice with a predicate
package main
import (
"github.com/spandigital/slices"
)
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8}
b := slices.Filter(a, func(v int) bool {
return v % 2 == 0 // even
})
println(b) // 2, 4, 6, 8
}
This function flats a 2 dimensional slice into a 1 dimensional slice,
There are variants Flatten3
, Flatten4
for 3 and 4 dimensions respectively.
package main
import (
"github.com/spandigital/slices"
)
func main() {
a := [][]int{{1, 2, 3, 4}, {5, 6}, {7, 8}}
b := slices.Flatten(a)
println(b) // 1, 2, 3, 4, 5, 6, 7, 8
}
Removes nil values from slices
Usage:
package main
import (
"github.com/spandigital/slices"
)
func main() {
type exampleStruct struct{}
a := new(exampleStruct)
b := new(exampleStruct)
c := new(exampleStruct)
filtered := slices.FilterNil([]*exampleStruct{a, b, nil, c, nil})
println(len(filtered)) // 3
}
package main
import (
"github.com/spandigital/slices"
)
func main() {
type exampleStruct struct{}
a := new(exampleStruct)
b := new(exampleStruct)
c := new(exampleStruct)
filtered := slices.FilterNil([]*exampleStruct{a, b, nil, c, nil})
println(len(filtered)) // 3
}
package main
import (
"github.com/spandigital/slices"
)
func main() {
println(slices.Contains([]int{1,2,3,4,5}, 4)) //true
println(slices.Contains([]string{"foo", "bar"}, "baz")) //false
}
package main
import (
"github.com/spandigital/slices"
)
func main() {
println(slices.Index([]int{1,2,3,4,5}, 4)) //3
println(slices.Contains([]string{"foo", "bar"}, "baz")) //-1
}
package main
import (
"github.com/spandigital/slices"
)
func main() {
println(slices.Intersection([]int{1,2,3,4,5}, []int{4,5,6,7,8})) // {4, 5}
println(slices.Intersection([]string{"foo", "bar"}, []string{"baz"})) // {}
}
package main
import (
"github.com/spandigital/slices"
)
func main() {
println(slices.Map([]int{1,2,3,4,5}, func(v int) {
return v*2
}) // 2, 4, 6, 8, 10
}