Created
August 5, 2019 15:55
-
-
Save HugoJBello/07271c32f271c2c10993fe831b826b50 to your computer and use it in GitHub Desktop.
flatten array script
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 main | |
import ( | |
"fmt" | |
"errors" | |
) | |
func main(){ | |
arrayExample := []interface{}{1, []interface{}{2, 3}, []interface{}{[]interface{}{4}}, []interface{}{5, []interface{}{6}}} | |
result, _ := flattenArray(arrayExample) | |
fmt.Println("Input array"); | |
fmt.Println(arrayExample); | |
fmt.Println("Result array"); | |
fmt.Println(result); | |
} | |
func flattenArray(array []interface{}) (flattened []int , err error){ | |
currentFlattened := []int{} | |
return flattenArrayRecursive(array, currentFlattened) | |
} | |
func flattenArrayRecursive(array interface{}, currentFlattened []int) (flattened []int , err error){ | |
switch copy := array.(type) { | |
case int : | |
currentFlattened = append(currentFlattened, copy) | |
case []int : | |
currentFlattened = append(currentFlattened, copy...) | |
case []interface{}: | |
for index := range copy { | |
currentFlattened, err = flattenArrayRecursive(copy[index], currentFlattened) | |
if err != nil { | |
return nil, err | |
} | |
} | |
default: | |
return nil, errors.New("Unable to flatten array") | |
} | |
return currentFlattened, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment