-
Notifications
You must be signed in to change notification settings - Fork 0
/
collection.go
95 lines (88 loc) · 1.76 KB
/
collection.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
package collection
import (
"bytes"
"encoding/gob"
)
type Collection []map[string]interface{}
// Where filters the collection by a given key / value pair.
func (c Collection) Where(key string, values ...interface{}) Collection {
var d = make([]map[string]interface{}, 0)
if len(values) < 1 {
for _, value := range c {
if isTrue(value[key]) {
d = append(d, value)
}
}
} else if len(values) < 2 {
for _, value := range c {
if value[key] == values[0] {
d = append(d, value)
}
}
} else {
switch values[0].(string) {
case "=":
for _, value := range c {
if value[key] == values[1] {
d = append(d, value)
}
}
}
}
return d
}
func (c Collection) Length() int {
return len(c)
}
func (c Collection) FirstGet(key string) interface{} {
return c[0][key]
}
func copyMap(m map[string]interface{}) map[string]interface{} {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
dec := gob.NewDecoder(&buf)
err := enc.Encode(m)
if err != nil {
panic(err)
}
var cm map[string]interface{}
err = dec.Decode(&cm)
if err != nil {
panic(err)
}
return cm
}
func isTrue(a interface{}) bool {
switch a.(type) {
case uint:
return a.(uint) != uint(0)
case uint8:
return a.(uint8) != uint8(0)
case uint16:
return a.(uint16) != uint16(0)
case uint32:
return a.(uint32) != uint32(0)
case uint64:
return a.(uint64) != uint64(0)
case int:
return a.(int) != int(0)
case int8:
return a.(int8) != int8(0)
case int16:
return a.(int16) != int16(0)
case int32:
return a.(int32) != int32(0)
case int64:
return a.(int64) != int64(0)
case float32:
return a.(float32) != float32(0)
case float64:
return a.(float64) != float64(0)
case string:
return a.(string) != ""
case bool:
return a.(bool)
default:
return false
}
}