forked from chenhg5/collection
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollection.go
729 lines (600 loc) · 20.8 KB
/
collection.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
package collection
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/shopspring/decimal"
)
// Collect transforms src into Collection. The src could be json string, []string,
// []map[string]interface{}, map[string]interface{}, []int, []int16, []int32, []int64,
// []float32, []float64, []interface{}.
func Collect(src interface{}) Collection {
switch src.(type) {
case string:
jsonStr := strings.TrimSpace(src.(string))
if jsonStr[0] == '[' {
var p []interface{}
if err := json.Unmarshal([]byte(jsonStr), &p); err != nil {
return BaseCollection{err: err}
}
return Collect(p)
}
if jsonStr[0] == '{' {
var p map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &p); err != nil {
return BaseCollection{err: err}
}
var c MapCollection
c.value = p
c.length = len(p)
return c
}
return BaseCollection{err: errors.New("invalid type")}
case []string:
var c StringArrayCollection
c.value = src.([]string)
c.length = len(src.([]string))
return c
case []map[string]interface{}:
var c MapArrayCollection
c.value = src.([]map[string]interface{})
c.length = len(src.([]map[string]interface{}))
return c
case map[string]interface{}:
var c MapCollection
c.value = src.(map[string]interface{})
c.length = len(src.(map[string]interface{}))
return c
case []int:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]int)))
for k, v := range src.([]int) {
d[k] = decimal.New(int64(v), 0)
}
c.value = d
c.length = len(src.([]int))
return c
case []int8:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]int8)))
for k, v := range src.([]int8) {
d[k] = decimal.New(int64(v), 0)
}
c.value = d
c.length = len(src.([]int8))
return c
case []int16:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]int16)))
for k, v := range src.([]int16) {
d[k] = decimal.New(int64(v), 0)
}
c.value = d
c.length = len(src.([]int16))
return c
case []int32:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]int32)))
for k, v := range src.([]int32) {
d[k] = decimal.New(int64(v), 0)
}
c.value = d
c.length = len(src.([]int32))
return c
case []int64:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]int64)))
for k, v := range src.([]int64) {
d[k] = decimal.New(v, 0)
}
c.value = d
c.length = len(src.([]int64))
return c
case []float32:
var c NumberArrayCollection
var f = make([]decimal.Decimal, len(src.([]float32)))
for k, v := range src.([]float32) {
f[k] = decimal.NewFromFloat32(v)
}
c.value = f
c.length = len(src.([]float32))
return c
case []float64:
var c NumberArrayCollection
var f = make([]decimal.Decimal, len(src.([]float64)))
for k, v := range src.([]float64) {
f[k] = decimal.NewFromFloat(v)
}
c.value = f
c.length = len(src.([]float64))
return c
case []interface{}:
if len(src.([]interface{})) == 0 {
return BaseCollection{err: errors.New("wrong value")}
}
switch src.([]interface{})[0].(type) {
case map[string]interface{}:
var c MapArrayCollection
var f = make([]map[string]interface{}, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = v.(map[string]interface{})
}
c.value = f
c.length = len(src.([]interface{}))
return c
case decimal.Decimal:
var c NumberArrayCollection
var f = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = v.(decimal.Decimal)
}
c.value = f
c.length = len(src.([]interface{}))
return c
case string:
var c StringArrayCollection
var f = make([]string, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = v.(string)
}
c.value = f
c.length = len(src.([]interface{}))
return c
case uint8:
var c StringArrayCollection
var f = make([]string, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = string(v.([]uint8))
}
c.value = f
c.length = len(src.([]interface{}))
return c
case int:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
d[k] = decimal.New(int64(v.(int)), 0)
}
c.value = d
c.length = len(src.([]interface{}))
return c
case int8:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
d[k] = decimal.New(int64(v.(int8)), 0)
}
c.value = d
c.length = len(src.([]interface{}))
return c
case int16:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
d[k] = decimal.New(int64(v.(int16)), 0)
}
c.value = d
c.length = len(src.([]interface{}))
return c
case int32:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
d[k] = decimal.New(int64(v.(int32)), 0)
}
c.value = d
c.length = len(src.([]interface{}))
return c
case int64:
var c NumberArrayCollection
var d = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
d[k] = decimal.New(v.(int64), 0)
}
c.value = d
c.length = len(src.([]interface{}))
return c
case float32:
var c NumberArrayCollection
var f = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = decimal.NewFromFloat32(v.(float32))
}
c.value = f
c.length = len(src.([]interface{}))
return c
case float64:
var c NumberArrayCollection
var f = make([]decimal.Decimal, len(src.([]interface{})))
for k, v := range src.([]interface{}) {
f[k] = decimal.NewFromFloat(v.(float64))
}
c.value = f
c.length = len(src.([]interface{}))
return c
default:
return BaseCollection{err: errors.New("wrong type")}
}
default:
return BaseCollection{err: errors.New("wrong type")}
}
}
type Collection interface {
Value() interface{}
// All returns the underlying array represented by the collection.
All() []interface{}
AllE() ([]interface{}, error)
// Length return the length of the collection.
Length() int
// ToStruct turn the collection to the specified struct using mapstructure.
// https://github.com/mitchellh/mapstructure
ToStruct(dist interface{})
ToStructE(dist interface{}) error
// Select select the keys of collection and delete others.
Select(keys ...string) Collection
// Column select the values of collection by the given key.
Column(key string) Collection
// Avg returns the average value of a given key.
Avg(key ...string) decimal.Decimal
// Sum returns the sum of all items in the collection.
Sum(key ...string) decimal.Decimal
// Min returns the minimum value of a given key.
Min(key ...string) decimal.Decimal
// Max returns the maximum value of a given key.
Max(key ...string) decimal.Decimal
// Join joins the collection's values with a string.
Join(delimiter string) string
JoinE(delimiter string) (string, error)
// Combine combines the values of the collection, as keys, with the values of another array or collection.
Combine(value []interface{}) Collection
// Count returns the total number of items in the collection.
Count() int
// Pluck retrieves all of the values for a given key.
Pluck(key string) Collection
// Mode returns the mode value of a given key.
Mode(key ...string) []interface{}
ModeE(key ...string) ([]interface{}, error)
// Only returns the items in the collection with the specified keys.
Only(keys []string) Collection
// Prepend adds an item to the beginning of the collection.
Prepend(values ...interface{}) Collection
// Pull removes and returns an item from the collection by its key.
Pull(key interface{}) Collection
// Put sets the given key and value in the collection:.
Put(key string, value interface{}) Collection
// SortBy sorts the collection by the given key.
SortBy(key string) Collection
// Take returns a new collection with the specified number of items.
Take(num int) Collection
// Chunk breaks the collection into multiple, smaller collections of a given size.
Chunk(num int) MultiDimensionalArrayCollection
// Collapse collapses a collection of arrays into a single, flat collection.
Collapse() Collection
// Concat appends the given array or collection values onto the end of the collection.
Concat(value interface{}) Collection
// Contains determines whether the collection contains a given item.
Contains(value ...interface{}) bool
ContainsE(value ...interface{}) (bool, error)
// CountBy counts the occurrences of values in the collection. By default, the method counts the occurrences of every element.
CountBy(callback ...interface{}) map[interface{}]int
CountByE(callback ...interface{}) (map[interface{}]int, error)
// CrossJoin cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations.
CrossJoin(array ...[]interface{}) MultiDimensionalArrayCollection
// Dd dumps the collection's items and ends execution of the script.
Dd()
DdE() error
// Diff compares the collection against another collection or a plain PHP array based on its values.
// This method will return the values in the original collection that are not present in the given collection.
Diff(interface{}) Collection
// DiffAssoc compares the collection against another collection or a plain PHP array based on its keys and values.
// This method will return the key / value pairs in the original collection that are not present in the given collection.
DiffAssoc(map[string]interface{}) Collection
// DiffKeys compares the collection against another collection or a plain PHP array based on its keys.
// This method will return the key / value pairs in the original collection that are not present in the given collection.
DiffKeys(map[string]interface{}) Collection
// Dump dumps the collection's items.
Dump()
DumpE() error
// Each iterates over the items in the collection and passes each item to a callback.
Each(func(item, value interface{}) (interface{}, bool)) Collection
// Every may be used to verify that all elements of a collection pass a given truth test.
Every(CB) bool
EveryE(CB) (bool, error)
// Except returns all items in the collection except for those with the specified keys.
Except([]string) Collection
// Filter filters the collection using the given callback, keeping only those items that pass a given truth test.
Filter(CB) Collection
// First returns the first element in the collection that passes a given truth test.
First(...CB) interface{}
FirstE(...CB) (interface{}, error)
// FirstWhere returns the first element in the collection with the given key / value pair.
FirstWhere(key string, values ...interface{}) map[string]interface{}
FirstWhereE(key string, values ...interface{}) (map[string]interface{}, error)
// FlatMap iterates through the collection and passes each value to the given callback.
FlatMap(func(value interface{}) interface{}) Collection
// Flip swaps the collection's keys with their corresponding values.
Flip() Collection
// Forget removes an item from the collection by its key.
Forget(string) Collection
// ForPage returns a new collection containing the items that would be present on a given page number.
ForPage(int, int) Collection
// Get returns the item at a given key. If the key does not exist, null is returned.
Get(string, ...interface{}) interface{}
GetE(string, ...interface{}) (interface{}, error)
// GroupBy groups the collection's items by a given key.
GroupBy(string) Collection
// Has determines if a given key exists in the collection.
Has(...string) bool
HasE(...string) (bool, error)
// Implode joins the items in a collection. Its arguments depend on the type of items in the collection.
Implode(string, string) string
ImplodeE(string, string) (string, error)
// Intersect removes any values from the original collection that are not present in the given array or collection.
Intersect([]string) Collection
// IntersectByKeys removes any keys from the original collection that are not present in the given array or collection.
IntersectByKeys(map[string]interface{}) Collection
// IsEmpty returns true if the collection is empty; otherwise, false is returned.
IsEmpty() bool
IsEmptyE() (bool, error)
// IsNotEmpty returns true if the collection is not empty; otherwise, false is returned.
IsNotEmpty() bool
IsNotEmptyE() (bool, error)
// KeyBy keys the collection by the given key. If multiple items have the same key, only the last one will
// appear in the new collection.
KeyBy(interface{}) Collection
// Keys returns all of the collection's keys.
Keys() Collection
// Last returns the last element in the collection that passes a given truth test.
Last(...CB) interface{}
LastE(...CB) (interface{}, error)
// MapToGroups groups the collection's items by the given callback.
MapToGroups(MapCB) Collection
// MapWithKeys iterates through the collection and passes each value to the given callback.
MapWithKeys(MapCB) Collection
// Median returns the median value of a given key.
Median(...string) decimal.Decimal
// Merge merges the given array or collection with the original collection. If a string key in the given items
// matches a string key in the original collection, the given items's value will overwrite the value in the
// original collection.
Merge(interface{}) Collection
// Pad will fill the array with the given value until the array reaches the specified size.
Pad(int, interface{}) Collection
// Partition separate elements that pass a given truth test from those that do not.
Partition(PartCB) (Collection, Collection)
// Pop removes and returns the last item from the collection.
Pop() interface{}
PopE() (interface{}, error)
// Push appends an item to the end of the collection.
Push(interface{}) Collection
// Random returns a random item from the collection.
Random(...int) Collection
// Reduce reduces the collection to a single value, passing the result of each iteration into the subsequent iteration.
Reduce(ReduceCB) interface{}
ReduceE(ReduceCB) (interface{}, error)
// Reject filters the collection using the given callback.
Reject(CB) Collection
// Reverse reverses the order of the collection's items, preserving the original keys.
Reverse() Collection
// Search searches the collection for the given value and returns its key if found. If the item is not found,
// -1 is returned.
Search(interface{}) int
SearchE(interface{}) (int, error)
// Shift removes and returns the first item from the collection.
Shift() Collection
// Shuffle randomly shuffles the items in the collection.
Shuffle() Collection
// Slice returns a slice of the collection starting at the given index.
Slice(...int) Collection
// Sort sorts the collection.
Sort() Collection
// SortByDesc has the same signature as the sortBy method, but will sort the collection in the opposite order.
SortByDesc() Collection
// Splice removes and returns a slice of items starting at the specified index.
Splice(index ...int) Collection
// Split breaks a collection into the given number of groups.
Split(int) Collection
// Unique returns all of the unique items in the collection.
Unique() Collection
// WhereIn filters the collection by a given key / value contained within the given array.
WhereIn(string, []interface{}) Collection
// WhereNotIn filters the collection by a given key / value not contained within the given array.
WhereNotIn(string, []interface{}) Collection
// ToJson converts the collection into a json string.
ToJson() string
ToJsonE() (string, error)
// ToNumberArray converts the collection into a plain golang slice which contains decimal.Decimal.
ToNumberArray() []decimal.Decimal
ToNumberArrayE() ([]decimal.Decimal, error)
// ToIntArray converts the collection into a plain golang slice which contains int.
ToIntArray() []int
ToIntArrayE() ([]int, error)
// ToInt64Array converts the collection into a plain golang slice which contains int.
ToInt64Array() []int64
ToInt64ArrayE() ([]int64, error)
// ToStringArray converts the collection into a plain golang slice which contains string.
ToStringArray() []string
ToStringArrayE() ([]string, error)
// ToMultiDimensionalArray converts the collection into a multi dimensional array.
ToMultiDimensionalArray() [][]interface{}
ToMultiDimensionalArrayE() ([][]interface{}, error)
// ToMap converts the collection into a plain golang map.
ToMap() map[string]interface{}
ToMapE() (map[string]interface{}, error)
// ToMapArray converts the collection into a plain golang slice which contains map.
ToMapArray() []map[string]interface{}
ToMapArrayE() ([]map[string]interface{}, error)
// Where filters the collection by a given key / value pair.
Where(key string, values ...interface{}) Collection
}
func newDecimalFromInterface(a interface{}) decimal.Decimal {
var d decimal.Decimal
switch a.(type) {
case uint:
d = decimal.New(int64(a.(uint)), 0)
case uint8:
d = decimal.New(int64(a.(uint8)), 0)
case uint16:
d = decimal.New(int64(a.(uint16)), 0)
case uint32:
d = decimal.New(int64(a.(uint32)), 0)
case uint64:
d = decimal.New(int64(a.(uint64)), 0)
case int:
d = decimal.New(int64(a.(int)), 0)
case int8:
d = decimal.New(int64(a.(int8)), 0)
case int16:
d = decimal.New(int64(a.(int16)), 0)
case int32:
d = decimal.New(int64(a.(int32)), 0)
case int64:
d = decimal.New(a.(int64), 0)
case float32:
d = decimal.NewFromFloat32(a.(float32))
case float64:
d = decimal.NewFromFloat(a.(float64))
default:
}
return d
}
func isTrue(a interface{}) bool {
switch a.(type) {
case uint:
return a.(uint) != uint(0)
case uint8:
return a.(uint8) != uint8(0)
case uint16:
return a.(uint16) != uint16(0)
case uint32:
return a.(uint32) != uint32(0)
case uint64:
return a.(uint64) != uint64(0)
case int:
return a.(int) != int(0)
case int8:
return a.(int8) != int8(0)
case int16:
return a.(int16) != int16(0)
case int32:
return a.(int32) != int32(0)
case int64:
return a.(int64) != int64(0)
case float32:
return a.(float32) != float32(0)
case float64:
return a.(float64) != float64(0)
case string:
return a.(string) != ""
case bool:
return a.(bool)
default:
return false
}
}
func nd(a interface{}) decimal.Decimal {
return newDecimalFromInterface(a)
}
type CB func(item, value interface{}) bool
type FilterFun func(value interface{}) interface{}
type MapCB func(map[string]interface{}) (string, interface{})
type PartCB func(int) bool
type ReduceCB func(interface{}, interface{}) interface{}
func copyMap(m map[string]interface{}) map[string]interface{} {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
dec := gob.NewDecoder(&buf)
err := enc.Encode(m)
if err != nil {
return nil
}
var cm map[string]interface{}
err = dec.Decode(&cm)
if err != nil {
return nil
}
return cm
}
func dd(c Collection) {
fmt.Println(c)
}
func dump(c Collection) {
fmt.Println(c)
}
func newDecimalArray(src interface{}) []decimal.Decimal {
switch src.(type) {
case []int:
var d = make([]decimal.Decimal, len(src.([]int)))
for k, v := range src.([]int) {
d[k] = decimal.New(int64(v), 0)
}
return d
case []int8:
var d = make([]decimal.Decimal, len(src.([]int8)))
for k, v := range src.([]int8) {
d[k] = decimal.New(int64(v), 0)
}
return d
case []int16:
var d = make([]decimal.Decimal, len(src.([]int16)))
for k, v := range src.([]int16) {
d[k] = decimal.New(int64(v), 0)
}
return d
case []int32:
var d = make([]decimal.Decimal, len(src.([]int32)))
for k, v := range src.([]int32) {
d[k] = decimal.New(int64(v), 0)
}
return d
case []int64:
var d = make([]decimal.Decimal, len(src.([]int64)))
for k, v := range src.([]int64) {
d[k] = decimal.New(v, 0)
}
return d
case []float32:
var f = make([]decimal.Decimal, len(src.([]float32)))
for k, v := range src.([]float32) {
f[k] = decimal.NewFromFloat32(v)
}
return f
case []float64:
var f = make([]decimal.Decimal, len(src.([]float64)))
for k, v := range src.([]float64) {
f[k] = decimal.NewFromFloat(v)
}
return f
default:
return nil
}
}
func qsort(arr []decimal.Decimal, order bool) []decimal.Decimal {
if len(arr) < 2 {
return arr
} else {
pivot := arr[0]
var less []decimal.Decimal
var greater []decimal.Decimal
for _, value := range arr[1:] {
if value.LessThanOrEqual(pivot) {
less = append(less, value)
} else {
greater = append(greater, value)
}
}
var result []decimal.Decimal
if order {
result = append(result, qsort(less, order)...)
result = append(result, pivot)
result = append(result, qsort(greater, order)...)
} else {
result = append(result, qsort(greater, order)...)
result = append(result, pivot)
result = append(result, qsort(less, order)...)
}
return result
}
}