1
exercism fetch go flatten-array

cases_test.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package flatten

// Source: exercism/problem-specifications
// Commit: d7a3c09 flatten-array: Add test case for no nesting (#744)
// Problem Specifications Version: 1.1.0

var testCases = []struct {
	description string
	input       interface{}
	expected    []interface{}
}{
	{
		description: "no nesting",
		input:       []interface{}{0, 1, 2},
		expected:    []interface{}{0, 1, 2},
	},
	{
		description: "flattens array with just integers present",
		input:       []interface{}{1, []interface{}{2, 3, 4, 5, 6, 7}, 8},
		expected:    []interface{}{1, 2, 3, 4, 5, 6, 7, 8},
	},
	{
		description: "5 level nesting",
		input:       []interface{}{0, 2, []interface{}{[]interface{}{2, 3}, 8, 100, 4, []interface{}{[]interface{}{[]interface{}{50}}}}, -2},
		expected:    []interface{}{0, 2, 2, 3, 8, 100, 4, 50, -2},
	},
	{
		description: "6 level nesting",
		input:       []interface{}{1, []interface{}{2, []interface{}{[]interface{}{3}}, []interface{}{4, []interface{}{[]interface{}{5}}}, 6, 7}, 8},
		expected:    []interface{}{1, 2, 3, 4, 5, 6, 7, 8},
	},
	{
		description: "6 level nest list with null values",
		input:       []interface{}{0, 2, []interface{}{[]interface{}{2, 3}, 8, []interface{}{[]interface{}{100}}, interface{}(nil), []interface{}{[]interface{}{interface{}(nil)}}}, -2},
		expected:    []interface{}{0, 2, 2, 3, 8, 100, -2},
	},
	{
		description: "all values in nested list are null",
		input:       []interface{}{interface{}(nil), []interface{}{[]interface{}{[]interface{}{interface{}(nil)}}}, interface{}(nil), interface{}(nil), []interface{}{[]interface{}{interface{}(nil), interface{}(nil)}, interface{}(nil)}, interface{}(nil)},
		expected:    []interface{}{},
	},
}

flatten_test.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package flatten

import (
	"reflect"
	"testing"
)

func TestFlatten(t *testing.T) {
	for _, tc := range testCases {
		if actual := Flatten(tc.input); !reflect.DeepEqual(actual, tc.expected) {
			t.Fatalf("FAIL: %s\nExpected: %v\nActual: %v", tc.description, tc.expected, actual)
		}
		t.Logf("PASS: %s", tc.description)
	}
}

func BenchmarkFlatten(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, tc := range testCases {
			Flatten(tc.input)
		}
	}
}