Skip to content

Instantly share code, notes, and snippets.

@bradclawsie
Last active October 8, 2019 01:45
Show Gist options
  • Save bradclawsie/40eaf686eac99343aa6363b67ba46b1d to your computer and use it in GitHub Desktop.
Save bradclawsie/40eaf686eac99343aa6363b67ba46b1d to your computer and use it in GitHub Desktop.
flatten.go
package main
// RUN IT! https://play.golang.org/p/hUrvvq_gBQX
import (
"fmt"
)
func flatten(iface interface{}) []int {
flattened := make([]int, 0)
type flattener func(interface{})
var recursiveFlatten flattener
recursiveFlatten = func(sublist interface{}) {
if theList, listOK := sublist.([]interface{}); listOK {
for i := 0; i < len(theList); i++ {
theInt, intOK := theList[i].(int)
if intOK {
flattened = append(flattened, theInt)
} else {
recursiveFlatten(theList[i])
}
}
}
}
recursiveFlatten(iface)
return flattened
}
func main() {
var one interface{} = 1
var two interface{} = 2
var three interface{} = 3
var four interface{} = 4
var five interface{} = 5
var six interface{} = 6
list := make([]interface{}, 0)
list = append(list, one)
list = append(list, two)
sublist0 := make([]interface{}, 0)
sublist0 = append(sublist0, three)
sublist1 := make([]interface{}, 0)
sublist1 = append(sublist1, five)
sublist1 = append(sublist1, six)
sublist0 = append(sublist0, sublist1)
sublist0 = append(sublist0, four)
list = append(list, sublist0)
fmt.Printf("%v\n", list)
fmt.Printf("%v\n", flatten(list))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment