forked from creachadair/mds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
106 lines (84 loc) · 2.03 KB
/
example_test.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
104
105
106
package mlink_test
import (
"fmt"
"strings"
"github.com/creachadair/mds/mlink"
)
func ExampleList() {
var lst mlink.List[string]
lst.At(0).Add(strings.Fields("A is for Amy who fell down the stairs")...)
// Find the first element of the list matching a predicate.
name := lst.Find(func(s string) bool {
return s == "Amy"
})
name.Set("Amélie") // change the value
name.Next() // move to the next element
name.Next() // ...and again
name.Truncate() // discard the rest of the list
name.Set("ran") // add a new last element
name.Push("far") // push a new element
// Add a new element at the end.
lst.End().Add("away")
// Remove the element we previously pushed.
name.Remove()
// Print out everything in the list.
lst.Each(func(s string) bool {
fmt.Print(" ", s)
return true
})
fmt.Println()
// Calculate the length of the list.
fmt.Println(lst.Len(), "items")
// Output:
// A is for Amélie who ran away
// 7 items
}
func ExampleList_Find() {
lst := mlink.NewList[int]()
lst.At(0).Add(2, 4, 6, 7, 8, 10)
if odd := lst.Find(isOdd); !odd.AtEnd() {
fmt.Printf("Found %d\n", odd.Get())
odd.Remove()
}
if odd := lst.Find(isOdd); odd.AtEnd() {
fmt.Println("no more odds")
}
// Output:
// Found 7
// no more odds
}
func isOdd(z int) bool { return z%2 == 1 }
func ExampleCursor_Next() {
var lst mlink.List[string]
lst.At(0).Add("apples", "pears", "plums", "cherries")
cur := lst.At(0)
for !cur.AtEnd() {
fmt.Print(cur.Get())
if cur.Next() {
fmt.Print(", ")
}
}
fmt.Println()
// Output:
// apples, pears, plums, cherries
}
func ExampleRing() {
r := mlink.RingOf("time", "flies", "like", "an", "arrow")
// Set the value of an existing element.
r.Value = "fruit"
// Splice new elements into a ring.
s := r.At(2).Join(mlink.RingOf("a", "banana"))
// Splice existing elements out of a ring.
s.Prev().Join(r)
// Iterate over the elements of a ring.
r.Each(func(s string) bool {
fmt.Println(s)
return true
})
// Output:
// fruit
// flies
// like
// a
// banana
}