本站源代码
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.

80 lines
2.4KB

  1. // Copyright (c) 2015, Emir Pasic. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package arraylist
  5. import "github.com/emirpasic/gods/containers"
  6. func assertEnumerableImplementation() {
  7. var _ containers.EnumerableWithIndex = (*List)(nil)
  8. }
  9. // Each calls the given function once for each element, passing that element's index and value.
  10. func (list *List) Each(f func(index int, value interface{})) {
  11. iterator := list.Iterator()
  12. for iterator.Next() {
  13. f(iterator.Index(), iterator.Value())
  14. }
  15. }
  16. // Map invokes the given function once for each element and returns a
  17. // container containing the values returned by the given function.
  18. func (list *List) Map(f func(index int, value interface{}) interface{}) *List {
  19. newList := &List{}
  20. iterator := list.Iterator()
  21. for iterator.Next() {
  22. newList.Add(f(iterator.Index(), iterator.Value()))
  23. }
  24. return newList
  25. }
  26. // Select returns a new container containing all elements for which the given function returns a true value.
  27. func (list *List) Select(f func(index int, value interface{}) bool) *List {
  28. newList := &List{}
  29. iterator := list.Iterator()
  30. for iterator.Next() {
  31. if f(iterator.Index(), iterator.Value()) {
  32. newList.Add(iterator.Value())
  33. }
  34. }
  35. return newList
  36. }
  37. // Any passes each element of the collection to the given function and
  38. // returns true if the function ever returns true for any element.
  39. func (list *List) Any(f func(index int, value interface{}) bool) bool {
  40. iterator := list.Iterator()
  41. for iterator.Next() {
  42. if f(iterator.Index(), iterator.Value()) {
  43. return true
  44. }
  45. }
  46. return false
  47. }
  48. // All passes each element of the collection to the given function and
  49. // returns true if the function returns true for all elements.
  50. func (list *List) All(f func(index int, value interface{}) bool) bool {
  51. iterator := list.Iterator()
  52. for iterator.Next() {
  53. if !f(iterator.Index(), iterator.Value()) {
  54. return false
  55. }
  56. }
  57. return true
  58. }
  59. // Find passes each element of the container to the given function and returns
  60. // the first (index,value) for which the function is true or -1,nil otherwise
  61. // if no element matches the criteria.
  62. func (list *List) Find(f func(index int, value interface{}) bool) (int, interface{}) {
  63. iterator := list.Iterator()
  64. for iterator.Next() {
  65. if f(iterator.Index(), iterator.Value()) {
  66. return iterator.Index(), iterator.Value()
  67. }
  68. }
  69. return -1, nil
  70. }
上海开阖软件有限公司 沪ICP备12045867号-1