Skip to content

Instantly share code, notes, and snippets.

@tywkeene
Created September 27, 2019 00:23
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 tywkeene/76e06ab4d9dc9827fa5934cc99038932 to your computer and use it in GitHub Desktop.
Save tywkeene/76e06ab4d9dc9827fa5934cc99038932 to your computer and use it in GitHub Desktop.
FlattenArray
package flatten
// FlattenArray flattens the array input, and places inputues into the array output
// When a nested array is encountered, FlattenArray will recurse into itself
//
// In the case that an element in input is not either int or []int, FlattenArray returns nil
func FlattenArray(input []interface{}) []int {
var output []int
for _, val := range input {
switch i := val.(type) {
case int:
output = append(output, i)
case []interface{}:
output = append(output, FlattenArray(i)...)
default:
return nil
}
}
return output
}
package flatten
import (
"reflect"
"testing"
)
type TestTable struct {
ExpectOutput []int
Data []interface{}
}
var testData = []TestTable{
TestTable{
ExpectOutput: nil,
Data: []interface{}{true, 2, []interface{}{[]interface{}{3}}, "a"},
},
TestTable{
ExpectOutput: []int{1, 2, 3, 4, 5},
Data: []interface{}{1, 2, []interface{}{[]interface{}{3}}, 4, 5},
},
TestTable{
ExpectOutput: []int{1, 2, 3, 4, 5, 6},
Data: []interface{}{
[]interface{}{
[]interface{}{
[]interface{}{1},
},
},
[]interface{}{
[]interface{}{
[]interface{}{
[]interface{}{2},
},
},
},
[]interface{}{
[]interface{}{
[]interface{}{3},
},
},
[]interface{}{
[]interface{}{
[]interface{}{4},
},
},
[]interface{}{
[]interface{}{
[]interface{}{5},
},
},
6,
},
},
TestTable{
ExpectOutput: []int{1, 2, 3, 4},
Data: []interface{}{1, 2, 3, 4},
},
}
func BenchmarkFlattenArray(b *testing.B) {
b.ReportAllocs()
for _, data := range testData {
for i := 0; i < b.N; i++ {
_ = FlattenArray(data.Data)
}
}
}
func TestFlattenArray(t *testing.T) {
var output []int
for i, data := range testData {
output = FlattenArray(data.Data)
if reflect.DeepEqual(output, data.ExpectOutput) == false {
t.Fatalf("Test %d failed: Expected output: %v got: %v\n", i, data.ExpectOutput, output)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment