-
Notifications
You must be signed in to change notification settings - Fork 1
/
concat.go
85 lines (68 loc) · 1.45 KB
/
concat.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
package flinx
// Append inserts an item to the end of a collection, so it becomes the last
// item.
func Append[T any](q Query[T], items ...T) Query[T] {
length := len(items)
var defaultValue T
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
index := 0
return func() (T, bool) {
i, ok := next()
if ok {
return i, ok
}
if index < length {
idx := index
index++
return items[idx], true
}
return defaultValue, false
}
},
}
}
// Concat concatenates two collections.
//
// The Concat method differs from the Union method because the Concat method
// returns all the original elements in the input sequences. The Union method
// returns only unique elements.
func Concat[T any](q, q2 Query[T]) Query[T] {
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
next2 := q2.Iterate()
use1 := true
return func() (item T, ok bool) {
if use1 {
item, ok = next()
if ok {
return
}
use1 = false
}
return next2()
}
},
}
}
// Prepend inserts an item to the beginning of a collection, so it becomes the
// first item.
func Prepend[T any](q Query[T], items ...T) Query[T] {
length := len(items)
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
index := 0
return func() (T, bool) {
if index < length {
idx := index
index++
return items[idx], true
}
return next()
}
},
}
}