-
Notifications
You must be signed in to change notification settings - Fork 3
/
helpers.go
102 lines (83 loc) · 2.12 KB
/
helpers.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
package fire
import (
"fmt"
)
// Map is a general purpose type to represent a map.
type Map map[string]interface{}
// SafeError wraps an error to indicate presentation safety.
type SafeError struct {
Err error
}
// E is a short-hand function to construct a safe error.
func E(format string, a ...interface{}) error {
return Safe(fmt.Errorf(format, a...))
}
// Safe wraps an error and marks it as safe. Wrapped errors are safe to be
// presented to the client if appropriate.
func Safe(err error) error {
return &SafeError{
Err: err,
}
}
// Error implements the error interface.
func (err *SafeError) Error() string {
return err.Err.Error()
}
// IsSafe can be used to check if an error has been wrapped using Safe.
func IsSafe(err error) bool {
_, ok := err.(*SafeError)
return ok
}
// Unique is a helper to get a unique list of object ids.
func Unique(list []string) []string {
// prepare map and list
m := make(map[string]bool)
l := make([]string, 0, len(list))
// add items not present in map
for _, id := range list {
if _, ok := m[id]; !ok {
m[id] = true
l = append(l, id)
}
}
return l
}
// Contains returns true if a list of strings contains another string.
func Contains(list []string, str string) bool {
for _, item := range list {
if item == str {
return true
}
}
return false
}
// Includes returns true if a list of strings includes another list of strings.
func Includes(all, subset []string) bool {
for _, item := range subset {
if !Contains(all, item) {
return false
}
}
return true
}
// Union will return a unique list with items from both lists.
func Union(listA, listB []string) []string {
// prepare new list
list := make([]string, 0, len(listA)+len(listB))
list = append(list, listA...)
list = append(list, listB...)
// return unique list
return Unique(list)
}
// Intersect will return the intersection of both lists.
func Intersect(listA, listB []string) []string {
// prepare new list
list := make([]string, 0, len(listA))
// add items that are part of both lists
for _, item := range listA {
if Contains(listB, item) {
list = append(list, item)
}
}
return list
}