Skip to content

Instantly share code, notes, and snippets.

@yulintan
Last active August 26, 2019 20:50
Show Gist options
  • Save yulintan/fed9c21db6aa939eb2ff9b4534e73300 to your computer and use it in GitHub Desktop.
Save yulintan/fed9c21db6aa939eb2ff9b4534e73300 to your computer and use it in GitHub Desktop.
Flatten array
package service
import "errors"
func FlatternArray(a interface{}, existing []int) ([]int, error) {
switch val := a.(type) {
case int:
return append(existing, val), nil
case []int:
return append(existing, val...), nil
case []interface{}:
var err error
for _, v := range val {
existing, err = FlatternArray(v, existing)
if err != nil {
return nil, errors.New("data type is not supported in interface")
}
}
return existing, nil
default:
return nil, errors.New("data type is not supported")
}
}
package service_test
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/yulintan/flatten-array"
)
var _ = Describe("Service", func() {
var (
a interface{}
existing []int
)
Context("when input is number", func() {
BeforeEach(func() {
existing = []int{1, 2}
a = 4
})
It("adds the number to the array", func() {
result, err := FlatternArray(a, existing)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal([]int{1, 2, 4}))
})
})
Context("when input is an array", func() {
BeforeEach(func() {
existing = []int{1, 2}
a = []int{3, 4}
})
It("merges arrays", func() {
result, err := FlatternArray(a, existing)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal([]int{1, 2, 3, 4}))
})
})
Context("when input is nested array", func() {
BeforeEach(func() {
existing = []int{1, 2}
a = []interface{}{3, []int{4, 5}, []interface{}{6, []int{7, 8}}}
})
It("breaks it down and recusively added them", func() {
result, err := FlatternArray(a, existing)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal([]int{1, 2, 3, 4, 5, 6, 7, 8}))
})
})
Context("when input type is not supported", func() {
BeforeEach(func() {
existing = []int{1, 2}
a = "abc"
})
It("returns error", func() {
_, err := FlatternArray(a, existing)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError(errors.New("data type is not supported")))
})
})
Context("when input type in nested array is not supported", func() {
BeforeEach(func() {
existing = []int{1, 2}
a = []interface{}{3, []int{4, 5}, []interface{}{6, "abc"}}
})
It("returns error", func() {
_, err := FlatternArray(a, existing)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError(errors.New("data type is not supported in interface")))
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment