-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterators.go
More file actions
44 lines (40 loc) · 1.49 KB
/
iterators.go
File metadata and controls
44 lines (40 loc) · 1.49 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
package array
// ForEach iterates over the array and calls the callback function for each element.
// The callback function is passed the value and index of the element.
func (a Array[T]) ForEach(cb func(value T, index int)) {
for i, v := range a {
cb(v, i)
}
}
// Filter iterates over the array and calls the callback function for each element.
// The callback function is passed the value and index of the element.
// It returns a new Array containing the elements for which the callback function returned true.
func (a Array[T]) Filter(cb func(value T, index int) bool) Array[T] {
var result = New[T]()
for i, v := range a {
if cb(v, i) {
result = append(result, v)
}
}
return result
}
// Map iterates over the array and calls the callback function for each element.
// The callback function is passed the value and index of the element.
// It returns a new Array containing the elements returned by the callback function.
func Map[T interface{}, K any](a Array[T], cb func(value T, index int) K) Array[K] {
var result = New[K]()
for i, v := range a {
result = append(result, cb(v, i))
}
return result
}
// Reduce iterates over the array and calls the callback function for each element.
// The callback function is passed the previous value, current value and index of the element.
// It returns the final value.
func Reduce[T interface{}, K any](a Array[T], cb func(pV K, cV T, index int) K, initial K) K {
var result = initial
for i, v := range a {
result = cb(result, v, i)
}
return result
}