-
Notifications
You must be signed in to change notification settings - Fork 0
/
flat.go
103 lines (92 loc) · 2.53 KB
/
flat.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package flatr
import "strconv"
// Flattener keep memory of options and transformers to flatten maps
type Flattener struct {
stack *stack[Entry]
prefix string
separator string
transformers []Transformer
scopedTrasformers map[string]Transformer
}
// New instantiate new flatter with provided options
// WithPrefix option add a prefix to keys
// WithSeparator option change default separator
// AddTransformer and AddScopedTransformer add custom transfomers that apply
// a custom function to each entry before processing it
func New(options ...Option) *Flattener {
f := &Flattener{
stack: &stack[Entry]{},
prefix: "",
separator: ".",
scopedTrasformers: make(map[string]Transformer),
}
for _, opt := range options {
opt(f)
}
return f
}
// Entry keep intermediate structure when flatten is ongoing and is passed to transformers
// tracked data include key and value of the node, height in the tree and if process have to
// stop without processing children nodes
type Entry struct {
K string
V any
H int
Stop bool
}
// Flat flatten a nested data structure (scalar, maps and slices) to a flat map.
// returns a map of 1 level when key is the full path of the field divided by a separator (default to .)
func (f *Flattener) Flat(toFlat any) (map[string]any, error) {
var err error
flatted := make(map[string]any)
f.stack.push(Entry{K: f.prefix, V: toFlat, H: 0, Stop: false})
for !f.stack.empty() {
e := f.stack.pop()
e, err = f.transformEntry(e, err)
if err != nil {
return flatted, err
}
f.flatmapNode(e, flatted)
}
return flatted, nil
}
func (f *Flattener) transformEntry(e Entry, err error) (Entry, error) {
transformers := f.transformers
fn, ok := f.scopedTrasformers[e.K]
if ok {
transformers = append(transformers, fn)
}
for _, fn := range transformers {
e, err = fn(e)
if err != nil {
return e, err
}
}
return e, nil
}
func (f *Flattener) flatmapNode(e Entry, flatted map[string]any) {
if e.Stop == true {
flatted[e.K] = e.V
return
}
switch e.V.(type) {
case map[string]any:
for k, m := range e.V.(map[string]any) {
nodeKey := joinKey(e.K, k, f.separator)
f.stack.push(Entry{K: nodeKey, V: m, H: e.H + 1})
}
case []any:
for i, v := range e.V.([]any) {
nodeKey := joinKey(e.K, strconv.Itoa(i), f.separator)
f.stack.push(Entry{K: nodeKey, V: v, H: e.H + 1})
}
default:
flatted[e.K] = e.V
}
}
func joinKey(parent, k, separator string) string {
if parent == "" {
return k
}
return parent + separator + k
}