Serge Bazanski | cc25bdf | 2018-10-25 14:02:58 +0200 | [diff] [blame] | 1 | package govalidator |
| 2 | |
| 3 | // Iterator is the function that accepts element of slice/array and its index |
| 4 | type Iterator func(interface{}, int) |
| 5 | |
| 6 | // ResultIterator is the function that accepts element of slice/array and its index and returns any result |
| 7 | type ResultIterator func(interface{}, int) interface{} |
| 8 | |
| 9 | // ConditionIterator is the function that accepts element of slice/array and its index and returns boolean |
| 10 | type ConditionIterator func(interface{}, int) bool |
| 11 | |
| 12 | // Each iterates over the slice and apply Iterator to every item |
| 13 | func 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. |
| 20 | func 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. |
| 29 | func 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. |
| 39 | func 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. |
| 50 | func 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 | } |