Created
April 8, 2019 16:29
-
-
Save jozuenoon/fee9877e5dd58c243f484a847f734481 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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