-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathexample_tsslice_test.go
More file actions
153 lines (103 loc) · 2.15 KB
/
example_tsslice_test.go
File metadata and controls
153 lines (103 loc) · 2.15 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package tsslice_test
import (
"fmt"
"sort"
"sync"
"github.com/Vonage/gosrvlib/pkg/threadsafe/tsslice"
)
func ExampleSet() {
mux := &sync.Mutex{}
s := make([]string, 2)
tsslice.Set(mux, s, 0, "Hello")
tsslice.Set(mux, s, 1, "World")
fmt.Println(s)
// Output:
// [Hello World]
}
func ExampleGet() {
mux := &sync.RWMutex{}
s := []string{"Hello", "World"}
fmt.Println(tsslice.Get(mux, s, 0))
fmt.Println(tsslice.Get(mux, s, 1))
// Output:
// Hello
// World
}
func ExampleLen() {
mux := &sync.RWMutex{}
s := []string{"Hello", "World"}
fmt.Println(tsslice.Len(mux, s))
// Output:
// 2
}
func ExampleAppend_simple() {
mux := &sync.Mutex{}
s := make([]string, 0, 2)
tsslice.Append(mux, &s, "Hello")
tsslice.Append(mux, &s, "World")
fmt.Println(s)
// Output:
// [Hello World]
}
func ExampleAppend_multiple() {
mux := &sync.Mutex{}
s := make([]string, 0, 2)
tsslice.Append(mux, &s, "Hello", "World")
fmt.Println(s)
// Output:
// [Hello World]
}
func ExampleAppend_slice() {
mux := &sync.Mutex{}
s := make([]string, 0, 2)
tsslice.Append(mux, &s, []string{"Hello", "World"}...)
fmt.Println(s)
// Output:
// [Hello World]
}
func ExampleAppend_concurrent() {
wg := &sync.WaitGroup{}
mux := &sync.RWMutex{}
maxgor := 5
s := make([]int, 0, maxgor)
for i := range maxgor {
wg.Add(1)
go func(item int) {
defer wg.Done()
tsslice.Append(mux, &s, item)
}(i)
}
wg.Wait()
sort.Ints(s)
fmt.Println(s)
// Output:
// [0 1 2 3 4]
}
func ExampleFilter() {
mux := &sync.RWMutex{}
s := []string{"Hello", "World", "Extra"}
filterFn := func(_ int, v string) bool { return v == "World" }
s2 := tsslice.Filter(mux, s, filterFn)
fmt.Println(s2)
// Output:
// [World]
}
func ExampleMap() {
mux := &sync.RWMutex{}
s := []string{"Hello", "World", "Extra"}
mapFn := func(k int, v string) int { return k + len(v) }
s2 := tsslice.Map(mux, s, mapFn)
fmt.Println(s2)
// Output:
// [5 6 7]
}
func ExampleReduce() {
mux := &sync.RWMutex{}
s := []int{2, 3, 5, 7, 11}
init := 97
reduceFn := func(k, v, r int) int { return k + v + r }
r := tsslice.Reduce(mux, s, init, reduceFn)
fmt.Println(r)
// Output:
// 135
}