Skip to content

Instantly share code, notes, and snippets.

@Ullaakut
Last active March 15, 2018 16:22
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 Ullaakut/cb1305ede48f2391090d57cde355074f to your computer and use it in GitHub Desktop.
Save Ullaakut/cb1305ede48f2391090d57cde355074f to your computer and use it in GitHub Desktop.
Flatten integers
package utils
// FlattenIntegers flattens nested slices of integers
func FlattenIntegers(slice []interface{}) []int {
var flat []int
for _, element := range slice {
switch element.(type) {
case []interface{}:
flat = append(flat, FlattenIntegers(element.([]interface{}))...)
case []int:
flat = append(flat, element.([]int)...)
case int:
flat = append(flat, element.(int))
}
}
return flat
}
package utils
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFlattenIntegers(t *testing.T) {
testCases := []struct {
description string
input []interface{}
expectedOutput []int
}{
{
description: "Input contains only integers",
input: []interface{}{
1,
2,
3,
4,
5,
},
expectedOutput: []int{1, 2, 3, 4, 5},
},
{
description: "Input contains only slices of integers",
input: []interface{}{
[]int{
1,
},
[]int{
2,
},
[]int{
3,
},
[]int{
4,
},
[]int{
5,
},
},
expectedOutput: []int{1, 2, 3, 4, 5},
},
{
description: "Input contains only nested slices of integers",
input: []interface{}{
[]interface{}{
[]interface{}{
[]int{
1,
},
},
},
[]interface{}{
[]interface{}{
[]int{
2,
},
},
},
[]interface{}{
[]interface{}{
[]int{
3,
},
},
},
},
expectedOutput: []int{1, 2, 3},
},
{
description: "Input contains only invalid types",
input: []interface{}{
"not a number",
[]interface{}{
[]interface{}{
"not a number",
},
},
},
expectedOutput: []int(nil),
},
{
description: "Input contains a mix of all possible cases",
input: []interface{}{
1,
[]int{
2,
3,
},
[]interface{}{
[]int{
4,
5,
},
},
"not a number",
[]interface{}{
[]interface{}{
"not a number",
},
},
},
expectedOutput: []int{1, 2, 3, 4, 5},
},
}
for index, testCase := range testCases {
assert.Equal(t, testCase.expectedOutput, FlattenIntegers(testCase.input), fmt.Sprintf("unexpected output for test %d", index))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment