Created
April 11, 2019 13:34
-
-
Save mertakman/6f5f4fcbcce5d20370a25ff93e440dcb to your computer and use it in GitHub Desktop.
Golang slice flatter
This file contains hidden or 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 flatten | |
| import ( | |
| "errors" | |
| "fmt" | |
| ) | |
| func Flatten(arr interface{}) ([]int, error) { | |
| return doFlatten([]int{}, arr) | |
| } | |
| func doFlatten(acc []int, arr interface{}) ([]int, error) { | |
| var err error | |
| switch v := arr.(type) { | |
| case []int: | |
| acc = append(acc, v...) | |
| case int: | |
| acc = append(acc, v) | |
| case []interface{}: | |
| for i := range v { | |
| acc, err = doFlatten(acc, v[i]) | |
| if err != nil { | |
| return nil, errors.New("Input contains item(s) that not type int or []int") | |
| } | |
| } | |
| default: | |
| return nil, errors.New("Input is not derivative of int nor []int") | |
| } | |
| return acc, nil | |
| } | |
This file contains hidden or 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 flatten | |
| import ( | |
| "errors" | |
| "reflect" | |
| "testing" | |
| ) | |
| func TestFlatten(t *testing.T) { | |
| result := []int{1, 2, 3, 4} | |
| response, err := Flatten([]interface{}{[]interface{}{1, 2, []int{3}}, 4}) | |
| if err != nil { | |
| t.Errorf(err.Error()) | |
| } | |
| if !reflect.DeepEqual(response, result) { | |
| t.Errorf("Result miscalculated . Should return %v , not %v .", result, response) | |
| } | |
| } | |
| func TestType(t *testing.T) { | |
| result := errors.New("Input contains item(s) that not type int or []int.") | |
| _, err := Flatten([]interface{}{[]interface{}{1, "2", []int{3}}, 4}) | |
| if reflect.DeepEqual(err, result) { | |
| t.Errorf("Cannot handle different types in slice.") | |
| } | |
| } | |
| func TestDifferentType(t *testing.T) { | |
| result := errors.New("Input is not derivative of int nor []int.") | |
| _, err := Flatten("false input") | |
| if reflect.DeepEqual(err, result) { | |
| t.Errorf("Cannot handle different type of input.") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment