-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
2594 lines (2158 loc) · 66.8 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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package flinx
import (
"fmt"
"strings"
"testing"
"time"
"github.com/kom0055/go-flinx/generics"
"gotest.tools/v3/assert"
)
func Test_ExampleKeyValue(t *testing.T) {
m := make(map[int]bool)
m[10] = true
assert.DeepEqual(t, Results(FromMap(m)), []KeyValue[int, bool]{{10, true}})
// Output:
// [{10 true}]
}
func TestExampleKeyValue_second(t *testing.T) {
input := []KeyValue[int, bool]{
{10, true},
}
m := ToMap(FromSlice(input))
assert.DeepEqual(t, m, map[int]bool{10: true})
// Output:
// map[10:true]
}
// The following code example demonstrates how
// to use Range to generate a slice of values.
func TestExampleRange(t *testing.T) {
// Generate a slice of integers from 1 to 10
// and then select their squares.
squares := ToSlice(Select(func(x int) int { return x * x })(Range(1, 10)))
assert.DeepEqual(t, squares, []int{1, 4, 9, 16, 25, 36, 49, 64, 81, 100})
//Output:
//1
//4
//9
//16
//25
//36
//49
//64
//81
//100
}
// The following code example demonstrates how to use Repeat
// to generate a slice of a repeated value.
func TestExampleRepeat(t *testing.T) {
slice := ToSlice(Repeat("I like programming.", 5))
assert.DeepEqual(t, slice,
[]string{"I like programming.", "I like programming.", "I like programming.",
"I like programming.", "I like programming."})
//Output:
//I like programming.
//I like programming.
//I like programming.
//I like programming.
//I like programming.
}
func TestExampleQuery(t *testing.T) {
query := Where(func(i int) bool {
return i <= 3
})(FromSlice([]int{1, 2, 3, 4, 5}))
slice := ToSlice(query)
assert.DeepEqual(t, slice, []int{1, 2, 3})
// Output:
// 1
// 2
// 3
}
// The following code example demonstrates how to use Aggregate function
func TestExampleQuery_Aggregate(t *testing.T) {
fruits := []string{"apple", "mango", "orange", "passionfruit", "grape"}
aggreFn := Aggregate(func(r, i string) string {
if len(r) > len(i) {
return r
}
return i
})
// Determine which string in the slice is the longest.
longestName := aggreFn(FromSlice(fruits))
assert.DeepEqual(t, longestName, "passionfruit")
// Output:
// passionfruit
}
// The following code example demonstrates how to use AggregateWithSeed function
func TestExampleQuery_AggregateWithSeed(t *testing.T) {
ints := []int{4, 8, 8, 3, 9, 0, 7, 8, 2}
aggreFn := AggregateWithSeed(0, func(total, next int) int {
if next%2 == 0 {
return total + 1
}
return total
})
// Count the even numbers in the array, using a seed value of 0.
numEven := aggreFn(FromSlice(ints))
assert.DeepEqual(t, numEven, 6)
// Output:
// The number of even integers is: 6
}
// The following code example demonstrates how to use AggregateWithSeedBy function
func TestExampleQuery_AggregateWithSeedBy(t *testing.T) {
input := []string{"apple", "mango", "orange", "passionfruit", "grape"}
aggreFn := AggregateWithSeedBy("banana", func(longest, next string) string {
if len(longest) > len(next) {
return longest
}
return next
}, func(result string) string {
return fmt.Sprintf("The fruit with the longest name is %s.", result)
})
// Determine whether any string in the array is longer than "banana".
longestName := aggreFn(FromSlice(input))
assert.DeepEqual(t, longestName, "The fruit with the longest name is passionfruit.")
// Output:
// The fruit with the longest name is passionfruit.
}
// The following code example demonstrates how to
// use Distinct to return distinct elements from a slice of integers.
func TestExampleOrderedQuery_Distinct(t *testing.T) {
ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
orderByFn := OrderBy(generics.NumericCompare[int], func(i int) int {
return i
})
distinctAges := ToSlice(Distinct(orderByFn(FromSlice(ages)).Query))
assert.DeepEqual(t, distinctAges, []int{17, 21, 46, 55})
// Output:
// [17 21 46 55]
}
// The following code example demonstrates how to
// use DistinctBy to return distinct elements from a ordered slice of elements.
func TestExampleOrderedQuery_DistinctBy(t *testing.T) {
type Product struct {
Name string
Code int
}
products := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
distinctByFn := DistinctBy(func(item Product) int {
return item.Code
})
orderByFn := OrderBy(
strings.Compare, func(item Product) string {
return item.Name
},
)
//Order and exclude duplicates.
noduplicates := ToSlice(distinctByFn(orderByFn(FromSlice(products)).Query))
assert.DeepEqual(t, noduplicates, []Product{{Name: "apple", Code: 9}, {Name: "lemon", Code: 12}, {Name: "orange", Code: 4}})
// Output:
// apple 9
// lemon 12
// orange 4
}
// The following code example demonstrates how to use ThenBy to perform
// a secondary ordering of the elements in a slice.
func TestExampleOrderedQuery_ThenBy(t *testing.T) {
fruits := []string{"grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry"}
// Sort the strings first by their length and then
//alphabetically by passing the identity selector function.
thenByFn := ThenBy(strings.Compare, func(fruit string) string {
return fruit
})
orderByFn := OrderBy(generics.NumericCompare[int], func(fruit string) int {
return len(fruit)
})
query := ToSlice(thenByFn(orderByFn(FromSlice(fruits))).Query)
assert.DeepEqual(t, query, []string{"apple", "grape", "mango", "banana", "orange", "blueberry", "raspberry", "passionfruit"})
// Output:
// apple
// grape
// mango
// banana
// orange
// blueberry
// raspberry
// passionfruit
}
// The following code example demonstrates how to use All to determine
// whether all the elements in a slice satisfy a condition.
// Variable allStartWithB is true if all the pet names start with "B"
// or if the pets array is empty.
func TestExampleQuery_All(t *testing.T) {
type Pet struct {
Name string
Age int
}
pets := []Pet{
{Name: "Barley", Age: 10},
{Name: "Boots", Age: 4},
{Name: "Whiskers", Age: 6},
}
// Determine whether all pet names
// in the array start with 'B'.
allStartWithB := All(func(pet Pet) bool { return strings.HasPrefix(pet.Name, "B") })(FromSlice(pets))
assert.DeepEqual(t, allStartWithB, false)
// Output:
//
// All pet names start with 'B'? false
}
// The following code example demonstrates how to use Any to determine
// whether a slice contains any elements.
func TestExampleQuery_Any(t *testing.T) {
numbers := []int{1, 2}
hasElements := Any(FromSlice(numbers))
assert.DeepEqual(t, hasElements, true)
// Output:
// Are there any element in the list? true
}
// The following code example demonstrates how to use AnyWith
// to determine whether any element in a slice satisfies a condition.
func TestExampleQuery_AnyWith(t *testing.T) {
type Pet struct {
Name string
Age int
Vaccinated bool
}
pets := []Pet{
{Name: "Barley", Age: 8, Vaccinated: true},
{Name: "Boots", Age: 4, Vaccinated: false},
{Name: "Whiskers", Age: 1, Vaccinated: false},
}
// Determine whether any pets over age 1 are also unvaccinated.
unvaccinated := AnyWith(func(p Pet) bool { return p.Age > 1 && p.Vaccinated == false })(FromSlice(pets))
assert.DeepEqual(t, unvaccinated, true)
// Output:
//
// Are there any unvaccinated animals over age one? true
}
// The following code example demonstrates how to use Append
// to include an elements in the last position of a slice.
func TestExampleQuery_Append(t *testing.T) {
input := []int{1, 2, 3, 4}
q := Append(FromSlice(input), 5)
last, _ := Last(q)
assert.DeepEqual(t, last, 5)
// Output:
// 5
}
// The following code example demonstrates how to use Average
// to calculate the average of a slice of values.
func TestExampleQuery_Average(t *testing.T) {
grades := []int{78, 92, 100, 37, 81}
average := Average(FromSlice(grades))
assert.DeepEqual(t, average, 77.6)
// Output:
// 77.6
}
// The following code example demonstrates how to use Count
// to count the elements in an array.
func TestExampleQuery_Count(t *testing.T) {
fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
numberOfFruits := Count(FromSlice(fruits))
assert.DeepEqual(t, numberOfFruits, 6)
// Output:
// 6
}
// The following code example demonstrates how to use Contains
// to determine whether a slice contains a specific element.
func TestExampleQuery_Contains(t *testing.T) {
slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
has5 := Contains(5)(FromSlice(slice))
assert.DeepEqual(t, has5, true)
// Output:
// Does the slice contains 5? true
}
// The following code example demonstrates how to use CountWith
// to count the even numbers in an array.
func TestExampleQuery_CountWith(t *testing.T) {
slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evenCount := CountWith(func(item int) bool { return item%2 == 0 })(FromSlice(slice))
assert.DeepEqual(t, evenCount, 6)
// Output:
// 6
}
// The following example demonstrates how to use the DefaultIfEmpty
// method on the results of a group join to perform a left outer join.
//
// The first step in producing a left outer join of two collections is to perform
// an inner join by using a group join. In this example, the list of Person objects
// is inner-joined to the list of Pet objects based on a Person object that matches Pet.Owner.
//
// The second step is to include each element of the first (left) collection in the
// result set even if that element has no matches in the right collection.
// This is accomplished by calling DefaultIfEmpty on each sequence of matching
// elements from the group join.
// In this example, DefaultIfEmpty is called on each sequence of matching Pet elements.
// The method returns a collection that contains a single, default value if the sequence
// of matching Pet elements is empty for any Person element, thereby ensuring that each
// Person element is represented in the result collection.
func TestExampleQuery_DefaultIfEmpty(t *testing.T) {
type Person struct {
FirstName string
LastName string
}
type Pet struct {
Name string
Owner Person
}
magnus := Person{FirstName: "Magnus", LastName: "Hedlund"}
terry := Person{FirstName: "Terry", LastName: "Adams"}
charlotte := Person{FirstName: "Charlotte", LastName: "Weiss"}
arlene := Person{FirstName: "Arlene", LastName: "Huff"}
barley := Pet{Name: "Barley", Owner: terry}
boots := Pet{Name: "Boots", Owner: terry}
whiskers := Pet{Name: "Whiskers", Owner: charlotte}
bluemoon := Pet{Name: "Blue Moon", Owner: terry}
daisy := Pet{Name: "Daisy", Owner: magnus}
// Create two lists.
people := []Person{magnus, terry, charlotte, arlene}
pets := []Pet{barley, boots, whiskers, bluemoon, daisy}
groupJoinFn := GroupJoin(func(person Person) Person { return person },
func(pet Pet) Person { return pet.Owner },
func(person Person, pets []Pet) Group[Person, Pet] {
return Group[Person, Pet]{Key: person, Group: Results(FromSlice(pets))}
})
selectManyByFn := SelectManyBy(
func(g Group[Person, Pet]) Query[Pet] {
return DefaultIfEmpty(FromSlice(g.Group), Pet{})
},
func(pet Pet, group Group[Person, Pet]) string {
return fmt.Sprintf("%s: %s", group.Key.FirstName, pet.Name)
},
)
//(FromSlice(people),FromSlice(pets))
results := ToSlice(selectManyByFn(groupJoinFn(FromSlice(people), FromSlice(pets))))
assert.DeepEqual(t, results, []string{"Magnus: Daisy", "Terry: Barley", "Terry: Boots",
"Terry: Blue Moon", "Charlotte: Whiskers", "Arlene: "})
// Output:
// Magnus: Daisy
// Terry: Barley
// Terry: Boots
// Terry: Blue Moon
// Charlotte: Whiskers
// Arlene:
}
// The following code example demonstrates how to use Distinct
// to return distinct elements from a slice of integers.
func TestExampleQuery_Distinct(t *testing.T) {
ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
distinctAges := ToSlice(Distinct(FromSlice(ages)))
assert.DeepEqual(t, distinctAges, []int{21, 46, 55, 17})
// Output:
// [21 46 55 17]
}
// The following code example demonstrates how to
// use DistinctBy to return distinct elements from a ordered slice of elements.
func TestExampleQuery_DistinctBy(t *testing.T) {
type Product struct {
Name string
Code int
}
products := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
//Order and exclude duplicates.
noduplicates := ToSlice(DistinctBy(func(item Product) int { return item.Code })(FromSlice(products)))
assert.DeepEqual(t, noduplicates, []Product{{Name: "orange", Code: 4},
{Name: "apple", Code: 9}, {Name: "lemon", Code: 12}})
// Output:
// orange 4
// apple 9
// lemon 12
}
// The following code example demonstrates how to use the Except
// method to compare two slices of numbers and return elements
// that appear only in the first slice.
func TestExampleQuery_Except(t *testing.T) {
numbers1 := []float32{2.0, 2.1, 2.2, 2.3, 2.4, 2.5}
numbers2 := []float32{2.2}
onlyInFirstSet := ToSlice(Except(FromSlice(numbers1), FromSlice(numbers2)))
assert.DeepEqual(t, onlyInFirstSet, []float32{2, 2.1, 2.3, 2.4, 2.5})
// Output:
//2
//2.1
//2.3
//2.4
//2.5
}
// The following code example demonstrates how to use the Except
// method to compare two slices of numbers and return elements
// that appear only in the first slice.
func TestExampleQuery_ExceptBy(t *testing.T) {
type Product struct {
Name string
Code int
}
fruits1 := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
fruits2 := []Product{
{Name: "apple", Code: 9},
}
//Order and exclude duplicates.
except := ToSlice(ExceptBy(func(item Product) int {
return item.Code
})(FromSlice(fruits1), FromSlice(fruits2)))
assert.DeepEqual(t, except, []Product{{Name: "orange", Code: 4}, {Name: "lemon", Code: 12}})
// Output:
// orange 4
// lemon 12
}
// The following code example demonstrates how to use First
// to return the first element of an array.
func TestExampleQuery_First(t *testing.T) {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
n, _ := First(FromSlice(numbers))
assert.DeepEqual(t, n, 9)
// Output:
// 9
}
// The following code example demonstrates how to use FirstWith
// to return the first element of an array that satisfies a condition.
func TestExampleQuery_FirstWith(t *testing.T) {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
first, _ := FirstWith(func(item int) bool { return item > 80 })(FromSlice(numbers))
assert.DeepEqual(t, first, 92)
// Output:
// 92
}
// The following code example demonstrates how to use Intersect
// to return the elements that appear in each of two slices of integers.
func TestExampleQuery_Intersect(t *testing.T) {
id1 := []int{44, 26, 92, 30, 71, 38}
id2 := []int{39, 59, 83, 47, 26, 4, 30}
both := ToSlice(Intersect(FromSlice(id1), FromSlice(id2)))
assert.DeepEqual(t, both, []int{26, 30})
// Output:
// 26
// 30
}
// The following code example demonstrates how to use IntersectBy
// to return the elements that appear in each of two slices of products with same Code.
func TestExampleQuery_IntersectBy(t *testing.T) {
type Product struct {
Name string
Code int
}
store1 := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
}
store2 := []Product{
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
duplicates := ToSlice(IntersectBy(func(p Product) int {
return p.Code
})(FromSlice(store1), FromSlice(store2)))
assert.DeepEqual(t, duplicates, []Product{{Name: "apple", Code: 9}})
// Output:
// apple 9
}
// The following code example demonstrates how to use Last
// to return the last element of an array.
func TestExampleQuery_Last(t *testing.T) {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 67, 12, 19}
last, _ := Last(FromSlice(numbers))
assert.DeepEqual(t, last, 19)
//Output:
//19
}
// The following code example demonstrates how to use LastWith
// to return the last element of an array.
func TestExampleQuery_LastWith(t *testing.T) {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 67, 12, 19}
last, _ := LastWith(func(n int) bool { return n > 80 })(FromSlice(numbers))
assert.DeepEqual(t, last, 87)
//Output:
//87
}
// The following code example demonstrates how to use Max
// to determine the maximum value in a slice.
func TestExampleQuery_Max(t *testing.T) {
numbers := []int64{4294967296, 466855135, 81125}
last, _ := Max(func(i, j int64) int {
return int(i - j)
})(FromSlice(numbers))
assert.DeepEqual(t, last, int64(4294967296))
//Output:
//4294967296
}
// The following code example demonstrates how to use Min
// to determine the minimum value in a slice.
func TestExampleQuery_Min(t *testing.T) {
grades := []int{78, 92, 99, 37, 81}
min, _ := Min(func(i, j int) int {
return i - j
})(FromSlice(grades))
assert.DeepEqual(t, min, 37)
//Output:
//37
}
// The following code example demonstrates how to use OrderByDescending
// to sort the elements of a slice in descending order by using a selector function
func TestExampleQuery_OrderByDescending(t *testing.T) {
names := []string{"Ned", "Ben", "Susan"}
result := ToSlice(OrderByDescending(
strings.Compare, Self[string],
)(FromSlice(names)).Query)
assert.DeepEqual(t, result, []string{"Susan", "Ned", "Ben"})
// Output:
// [Susan Ned Ben]
}
// The following code example demonstrates how to use ThenByDescending to perform
// a secondary ordering of the elements in a slice in descending order.
func TestExampleOrderedQuery_ThenByDescending(t *testing.T) {
fruits := []string{"apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"}
// Sort the strings first ascending by their length and
// then descending using a custom case insensitive comparer.
query := ToSlice(ThenByDescending(generics.NumericCompare[byte], func(i string) byte {
return i[0]
})(OrderBy(generics.NumericCompare[int], func(i string) int {
return len(i)
})(FromSlice(fruits))).Query)
assert.DeepEqual(t, query, []string{"apPLe", "apple", "apPLE", "APple", "orange", "baNanA", "ORANGE", "BAnana"})
// Output:
// apPLe
// apple
// apPLE
// APple
// orange
// baNanA
// ORANGE
// BAnana
}
// The following code example demonstrates how to use Concat
// to concatenate two slices.
func TestExampleQuery_Concat(t *testing.T) {
assert.DeepEqual(t, Results(Concat(FromSlice([]int{1, 2, 3}), FromSlice([]int{4, 5, 6}))),
[]int{1, 2, 3, 4, 5, 6})
// Output:
// [1 2 3 4 5 6]
}
func TestExampleQuery_GroupBy(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
res := Results(OrderBy(func(i, j int) int {
return i - j
}, func(g Group[int, int]) int {
return g.Key
})(GroupBy(func(i int) int { return i % 2 }, func(i int) int {
return i
})(FromSlice(input))).Query)
assert.DeepEqual(t, res,
[]Group[int, int]{{Key: 0, Group: []int{2, 4, 6, 8}}, {Key: 1, Group: []int{1, 3, 5, 7, 9}}})
// Output:
// [{0 [2 4 6 8]} {1 [1 3 5 7 9]}]
}
// The following code example demonstrates how to use GroupJoin
// to perform a grouped join on two slices
func TestExampleQuery_GroupJoin(t *testing.T) {
fruits := []string{
"apple",
"banana",
"apricot",
"cherry",
"clementine",
}
res := Results(GroupJoin(
func(i rune) rune { return i },
func(i string) rune { return []rune(i)[0] },
func(outer rune, inners []string) KeyValue[rune, []string] {
return KeyValue[rune, []string]{outer, inners}
},
)(FromString("abc"), FromSlice(fruits)))
assert.DeepEqual(t, res,
[]KeyValue[rune, []string]{{Key: 'a', Value: []string{"apple", "apricot"}},
{Key: 'b', Value: []string{"banana"}},
{Key: 'c', Value: []string{"cherry", "clementine"}}})
// Output:
// [{a [apple apricot]} {b [banana]} {c [cherry clementine]}]
}
// The following code example demonstrates how to use IndexOf
// to retrieve the position of an item in the array and then
// update that item.
func TestExampleQuery_IndexOf(t *testing.T) {
type Item struct {
ID uint64
Name string
}
items := []Item{
{
ID: 1,
Name: "Joe",
},
{
ID: 2,
Name: "Bob",
},
{
ID: 3,
Name: "Rickster",
},
{
ID: 4,
Name: "Jim",
},
}
index := IndexOf(func(item Item) bool {
return item.Name == "Rickster"
})(FromSlice(items))
assert.DeepEqual(t, index, 2)
if index >= 0 {
// We found the item in the array. Change the name using the index.
items[index].Name = "Joshua"
fmt.Println("Item found at:", index, "new name:", items[index].Name)
}
// Output:
// Item found at: 2 new name: Joshua
}
// The following code example demonstrates how to use Join
// to perform an inner join of two slices based on a common key.
func TestExampleQuery_Join(t *testing.T) {
fruits := []string{
"apple",
"banana",
"apricot",
"cherry",
"clementine",
}
q :=
Join(
Self[int],
func(i string) int {
return len(i)
},
func(outer int, inner string) KeyValue[int, string] {
return KeyValue[int, string]{outer, inner}
},
)(Range(1, 10), FromSlice(fruits))
assert.DeepEqual(t, Results(q), []KeyValue[int, string]{
{Key: 5, Value: "apple"}, {Key: 6, Value: "banana"}, {Key: 6, Value: "cherry"},
{Key: 7, Value: "apricot"}, {Key: 10, Value: "clementine"},
})
// Output:
// [{5 apple} {6 banana} {6 cherry} {7 apricot} {10 clementine}]
}
// The following code example demonstrates how to use OrderBy
// to sort the elements of a slice.
func TestExampleQuery_OrderBy(t *testing.T) {
q := ThenByDescending(
generics.NumericCompare[int],
Self[int],
)(OrderBy(
generics.NumericCompare[int],
func(v int) int {
return v % 2
},
)(Range(1, 10)))
assert.DeepEqual(t, Results(q.Query), []int{10, 8, 6, 4, 2, 9, 7, 5, 3, 1})
// Output:
// [10 8 6 4 2 9 7 5 3 1]
}
// The following code example demonstrates how to use Prepend
// to include an elements in the first position of a slice.
func TestExampleQuery_Prepend(t *testing.T) {
input := []int{2, 3, 4, 5}
first, _ := First(Prepend(FromSlice(input), 1))
assert.DeepEqual(t, first, 1)
// Output:
// 1
}
// The following code example demonstrates how to use Reverse
// to reverse the order of elements in a string.
func TestExampleQuery_Reverse(t *testing.T) {
input := "apple"
output := ToSlice(Reverse(FromString(input)))
assert.DeepEqual(t, string(output), "elppa")
// Output:
// elppa
}
// The following code example demonstrates how to use Select
// to project over a slice of values.
func TestExampleQuery_Select(t *testing.T) {
squares := ToSlice(Select(func(x int) int {
return x * x
})(Range(1, 10)))
assert.DeepEqual(t, squares, []int{1, 4, 9, 16, 25, 36, 49, 64, 81, 100})
// Output:
// [1 4 9 16 25 36 49 64 81 100]
}
func TestExampleQuery_SelectMany(t *testing.T) {
input := [][]int{{1, 2, 3}, {4, 5, 6, 7}}
res := Results(SelectMany(func(i []int) Query[int] {
return FromSlice(i)
})(FromSlice(input)))
assert.DeepEqual(t, res, []int{1, 2, 3, 4, 5, 6, 7})
// Output:
// [1 2 3 4 5 6 7]
}
// The following code example demonstrates how to use Select
// to project over a slice of values and use the index of each element.
func TestExampleQuery_SelectIndexed(t *testing.T) {
fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
result := ToSlice(SelectIndexed(func(i int, s string) string {
return s[:i]
})(FromSlice(fruits)))
assert.DeepEqual(t, result, []string{"", "b", "ma", "ora", "pass", "grape"})
// Output:
// [ b ma ora pass grape]
}
// The following code example demonstrates how to use SelectManyByIndexed
// to perform a one-to-many projection over an array and use the index of each outer element.
func TestExampleQuery_SelectManyByIndexed(t *testing.T) {
type Pet struct {
Name string
}
type Person struct {
Name string
Pets []Pet
}
magnus := Person{
Name: "Hedlund, Magnus",
Pets: []Pet{{Name: "Daisy"}},
}
terry := Person{
Name: "Adams, Terry",
Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
}
charlotte := Person{
Name: "Weiss, Charlotte",
Pets: []Pet{{Name: "Whiskers"}},
}
people := []Person{magnus, terry, charlotte}
results := ToSlice(SelectManyByIndexed(
func(i int, p Person) Query[string] {
return Select(func(pet Pet) string {
return fmt.Sprintf("%d - %s", i, pet.Name)
})(FromSlice(p.Pets))
},
func(pet string, person Person) string {
return fmt.Sprintf("Pet: %s, Owner: %s", pet, person.Name)
},
)(FromSlice(people)))
assert.DeepEqual(t, results, []string{"Pet: 0 - Daisy, Owner: Hedlund, Magnus",
"Pet: 1 - Barley, Owner: Adams, Terry",
"Pet: 1 - Boots, Owner: Adams, Terry",
"Pet: 2 - Whiskers, Owner: Weiss, Charlotte",
})
// Output:
// Pet: 0 - Daisy, Owner: Hedlund, Magnus
// Pet: 1 - Barley, Owner: Adams, Terry
// Pet: 1 - Boots, Owner: Adams, Terry
// Pet: 2 - Whiskers, Owner: Weiss, Charlotte
}
// The following code example demonstrates how to use SelectManyIndexed
// to perform a one-to-many projection over an slice of log data and print out their contents.
func TestExampleQuery_SelectManyIndexed(t *testing.T) {
type LogFile struct {
Name string
Lines []string
}
file1 := LogFile{
Name: "file1.log",
Lines: []string{
"INFO: 2013/11/05 18:11:01 main.go:44: Special Information",
"WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about",
"ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed",
},
}
file2 := LogFile{
Name: "file2.log",
Lines: []string{
"INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok",
},
}
file3 := LogFile{
Name: "file3.log",
Lines: []string{
"2013/11/05 18:42:26 Hello World",
},
}
logFiles := []LogFile{file1, file2, file3}
results := ToSlice(SelectManyIndexed(
func(fileIndex int, file LogFile) Query[string] {
return SelectIndexed(
func(lineIndex int, line string) string {
return fmt.Sprintf("File:[%d] - %s => line: %d - %s", fileIndex+1, file.Name, lineIndex+1, line)
},
)(FromSlice(file.Lines))
},
)(FromSlice(logFiles)))
assert.DeepEqual(t, results, []string{
"File:[1] - file1.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:44: Special Information",
"File:[1] - file1.log => line: 2 - WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about",
"File:[1] - file1.log => line: 3 - ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed",
"File:[2] - file2.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok",
"File:[3] - file3.log => line: 1 - 2013/11/05 18:42:26 Hello World",
})
// Output:
// File:[1] - file1.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:44: Special Information
// File:[1] - file1.log => line: 2 - WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about
// File:[1] - file1.log => line: 3 - ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed
// File:[2] - file2.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok
// File:[3] - file3.log => line: 1 - 2013/11/05 18:42:26 Hello World
}
// The following code example demonstrates how to use SelectMany
// to perform a one-to-many projection over a slice
func TestExampleQuery_SelectManyBy(t *testing.T) {
type Pet struct {
Name string
}
type Person struct {
Name string
Pets []Pet
}
magnus := Person{
Name: "Hedlund, Magnus",