blob: 5bace2654d3bc561584ae68269de882778b208f2 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001package govalidator
2
3// Iterator is the function that accepts element of slice/array and its index
4type Iterator func(interface{}, int)
5
6// ResultIterator is the function that accepts element of slice/array and its index and returns any result
7type ResultIterator func(interface{}, int) interface{}
8
9// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
10type ConditionIterator func(interface{}, int) bool
11
12// Each iterates over the slice and apply Iterator to every item
13func Each(array []interface{}, iterator Iterator) {
14 for index, data := range array {
15 iterator(data, index)
16 }
17}
18
19// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
20func Map(array []interface{}, iterator ResultIterator) []interface{} {
21 var result = make([]interface{}, len(array))
22 for index, data := range array {
23 result[index] = iterator(data, index)
24 }
25 return result
26}
27
28// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
29func Find(array []interface{}, iterator ConditionIterator) interface{} {
30 for index, data := range array {
31 if iterator(data, index) {
32 return data
33 }
34 }
35 return nil
36}
37
38// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
39func Filter(array []interface{}, iterator ConditionIterator) []interface{} {
40 var result = make([]interface{}, 0)
41 for index, data := range array {
42 if iterator(data, index) {
43 result = append(result, data)
44 }
45 }
46 return result
47}
48
49// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
50func Count(array []interface{}, iterator ConditionIterator) int {
51 count := 0
52 for index, data := range array {
53 if iterator(data, index) {
54 count = count + 1
55 }
56 }
57 return count
58}