Skip to content

Instantly share code, notes, and snippets.

@jozuenoon
Created April 8, 2019 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jozuenoon/fee9877e5dd58c243f484a847f734481 to your computer and use it in GitHub Desktop.
Save jozuenoon/fee9877e5dd58c243f484a847f734481 to your computer and use it in GitHub Desktop.
package nestedslices
type out struct {
data []int
}
func (o *out) Append(v int) {
o.data = append(o.data, v)
}
func FlatSlice(in []interface{}) []int {
o := out{}
flatSlice(in, &o)
return o.data
}
func flatSlice(in []interface{}, o *out) {
for _, val := range in {
v := val
switch vt := v.(type) {
case int:
o.Append(vt)
case []interface{}:
flatSlice(vt, o)
}
}
}
package nestedslices
import (
"reflect"
"testing"
)
func TestFlatSlice(t *testing.T) {
tests := []struct {
name string
in []interface{}
want []int
}{
{"basic", []interface{}{1, 2, 3, 4}, []int{1, 2, 3, 4}},
{"basic", []interface{}{[]interface{}{1, 2, 3}, 4}, []int{1, 2, 3, 4}},
{"basic", []interface{}{[]interface{}{1, 2, []interface{}{3}}, 4}, []int{1, 2, 3, 4}},
{"basic", []interface{}{[]interface{}{1, 2, []interface{}{3, 4, 5}}, 4}, []int{1, 2, 3, 4, 5, 4}},
{"basic", []interface{}{[]interface{}{1, 2, []interface{}{[]interface{}{3, 3, 3}, 4, 5}}, 4}, []int{1, 2, 3, 3, 3, 4, 5, 4}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := FlatSlice(tt.in); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FlatSlice() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment