summaryrefslogtreecommitdiffstats
path: root/cmd/jp/split.go
blob: 2220c372c5db690ebf1cc3d72f04846a213ebfde (plain)
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
43
44
45
46
47
48
49
50
51
package main

import "reflect"

var indexableKind = map[reflect.Kind]bool{
	reflect.Slice: true,
	reflect.Array: true,
}

func flatten(in [][]reflect.Value) (out []reflect.Value) {
	for _, a := range in {
		for _, v := range a {
			if !v.IsValid() {
				continue
			}
			if indexableKind[v.Kind()] {
				sub := make([]reflect.Value, v.Len())
				for j := 0; j < v.Len(); j++ {
					sub = append(sub, v.Index(j))
				}
				out = append(out, flatten([][]reflect.Value{sub})...)
				continue
			}
			if v.CanInterface() {
				if sub, ok := v.Interface().([]interface{}); ok {
					for i := range sub {
						out = append(out, reflect.ValueOf(sub[i]))
					}
					continue
				}
			}
			out = append(out, v)
		}
	}
	return
}

func split(in [][]reflect.Value) (x, y []reflect.Value) {
	flat := flatten(in)
	n := len(flat)
	x = make([]reflect.Value, 0, n/2)
	y = make([]reflect.Value, 0, n/2)
	for i := range flat {
		if i&1 == 0 {
			x = append(x, flat[i])
		} else {
			y = append(y, flat[i])
		}
	}
	return
}