本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.9KB

  1. package govalidator
  2. // Iterator is the function that accepts element of slice/array and its index
  3. type Iterator func(interface{}, int)
  4. // ResultIterator is the function that accepts element of slice/array and its index and returns any result
  5. type ResultIterator func(interface{}, int) interface{}
  6. // ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
  7. type ConditionIterator func(interface{}, int) bool
  8. // Each iterates over the slice and apply Iterator to every item
  9. func Each(array []interface{}, iterator Iterator) {
  10. for index, data := range array {
  11. iterator(data, index)
  12. }
  13. }
  14. // Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
  15. func Map(array []interface{}, iterator ResultIterator) []interface{} {
  16. var result = make([]interface{}, len(array))
  17. for index, data := range array {
  18. result[index] = iterator(data, index)
  19. }
  20. return result
  21. }
  22. // Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
  23. func Find(array []interface{}, iterator ConditionIterator) interface{} {
  24. for index, data := range array {
  25. if iterator(data, index) {
  26. return data
  27. }
  28. }
  29. return nil
  30. }
  31. // Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
  32. func Filter(array []interface{}, iterator ConditionIterator) []interface{} {
  33. var result = make([]interface{}, 0)
  34. for index, data := range array {
  35. if iterator(data, index) {
  36. result = append(result, data)
  37. }
  38. }
  39. return result
  40. }
  41. // Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
  42. func Count(array []interface{}, iterator ConditionIterator) int {
  43. count := 0
  44. for index, data := range array {
  45. if iterator(data, index) {
  46. count = count + 1
  47. }
  48. }
  49. return count
  50. }
上海开阖软件有限公司 沪ICP备12045867号-1