Skip to content

Instantly share code, notes, and snippets.

@thatnerdjosh
Created August 13, 2019 18:45
Show Gist options
  • Save thatnerdjosh/cf8b2412380c1607bc258a85c3e15eec to your computer and use it in GitHub Desktop.
Save thatnerdjosh/cf8b2412380c1607bc258a85c3e15eec to your computer and use it in GitHub Desktop.
FlattenSlice
package main
import(
"reflect"
)
// IsArrayType accepts an interface and returns whether it is an array
// This function will return false if it is not an array type
func IsArrayType(s interface{}) bool {
t := reflect.TypeOf(s)
switch t.Kind() {
case reflect.Slice:
return true
case reflect.Array:
return true
default:
return false
}
}
// FlattenNestedSlice is a recursive function.
// It accepts one or many interfaces and returns an arbitrarily/relatively flattened slice of interface
func FlattenNestedSlice(v ...interface{}) []interface{} {
list := []interface{}{}
for _, val := range v {
if IsArrayType(val) {
for _, z := range FlattenNestedSlice((val.([]interface{}))...) {
list = append(list, z)
}
} else {
list = append(list, val)
}
}
return list
}
package main
// TestFlattenNestedSlice tests FlattenNested Slice, provided valid input
func TestFlattenNestedSlice(t *testing.T) {
input := []interface{}{[]interface{}{1, 2, []interface{}{3}, 4}}
got := FlattenNestedSlice(input)
expected := []interface{}{1,2,3,4}
for i, v := range got { if v != expected[i] { t.Errorf("FlattenNestedSlice(%v) = %d; want 1", input, got) } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment