-
Notifications
You must be signed in to change notification settings - Fork 2
/
stringarray.go
76 lines (65 loc) · 1.79 KB
/
stringarray.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
package nkngomobile
import (
"encoding/json"
mathRand "math/rand"
"strings"
)
// StringArray is a wrapper type for gomobile compatibility. StringArray is not
// protected by lock and should not be read and write at the same time.
type StringArray struct{ elems []string }
// NewStringArray creates a StringArray from a list of string elements.
func NewStringArray(elems ...string) *StringArray {
return &StringArray{elems}
}
// NewStringArrayFromString creates a StringArray from a single string input.
// The input string will be split to string array by whitespace.
func NewStringArrayFromString(s string) *StringArray {
return &StringArray{strings.Fields(s)}
}
// Elems returns the string array elements.
func (sa *StringArray) Elems() []string {
if sa == nil {
return nil
}
return sa.elems
}
// Len returns the string array length.
func (sa *StringArray) Len() int {
return len(sa.Elems())
}
// Append adds an element to the string array.
func (sa *StringArray) Append(s string) {
sa.elems = append(sa.elems, s)
}
// Get gets an element to the string array.
func (sa *StringArray) Get(i int) string {
return sa.Elems()[i]
}
// RandomElem returns a randome element from the string array. The random number
// is generated using math/rand and thus not cryptographically secure.
func (sa *StringArray) RandomElem() string {
if sa.Len() == 0 {
return ""
}
return sa.Elems()[mathRand.Intn(sa.Len())]
}
// Join returns a single string by concatenates the elements
func (sa *StringArray) Join(separator string) string {
if sa == nil {
return ""
}
return strings.Join(sa.elems, separator)
}
func (sa *StringArray) GetJson() string {
if sa == nil || sa.Len() == 0 {
return "[]"
}
b, err := json.Marshal(sa.elems)
if err != nil {
return "[]"
}
if b == nil {
return "[]"
}
return string(b)
}