gitee.com/quant1x/gox@v1.21.2/util/singlylinkedlist/enumerable.go (about) 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 5 package singlylinkedlist 6 7 import ( 8 "gitee.com/quant1x/gox/util/internal" 9 ) 10 11 func assertEnumerableImplementation() { 12 var _ internal.EnumerableWithIndex = (*List)(nil) 13 } 14 15 // Each calls the given function once for each element, passing that element's index and value. 16 func (list *List) Each(f func(index int, value interface{})) { 17 iterator := list.Iterator() 18 for iterator.Next() { 19 f(iterator.Index(), iterator.Value()) 20 } 21 } 22 23 // Map invokes the given function once for each element and returns a 24 // container containing the values returned by the given function. 25 func (list *List) Map(f func(index int, value interface{}) interface{}) *List { 26 newList := &List{} 27 iterator := list.Iterator() 28 for iterator.Next() { 29 newList.Add(f(iterator.Index(), iterator.Value())) 30 } 31 return newList 32 } 33 34 // Select returns a new container containing all elements for which the given function returns a true value. 35 func (list *List) Select(f func(index int, value interface{}) bool) *List { 36 newList := &List{} 37 iterator := list.Iterator() 38 for iterator.Next() { 39 if f(iterator.Index(), iterator.Value()) { 40 newList.Add(iterator.Value()) 41 } 42 } 43 return newList 44 } 45 46 // Any passes each element of the container to the given function and 47 // returns true if the function ever returns true for any element. 48 func (list *List) Any(f func(index int, value interface{}) bool) bool { 49 iterator := list.Iterator() 50 for iterator.Next() { 51 if f(iterator.Index(), iterator.Value()) { 52 return true 53 } 54 } 55 return false 56 } 57 58 // All passes each element of the container to the given function and 59 // returns true if the function returns true for all elements. 60 func (list *List) All(f func(index int, value interface{}) bool) bool { 61 iterator := list.Iterator() 62 for iterator.Next() { 63 if !f(iterator.Index(), iterator.Value()) { 64 return false 65 } 66 } 67 return true 68 } 69 70 // Find passes each element of the container to the given function and returns 71 // the first (index,value) for which the function is true or -1,nil otherwise 72 // if no element matches the criteria. 73 func (list *List) Find(f func(index int, value interface{}) bool) (index int, value interface{}) { 74 iterator := list.Iterator() 75 for iterator.Next() { 76 if f(iterator.Index(), iterator.Value()) { 77 return iterator.Index(), iterator.Value() 78 } 79 } 80 return -1, nil 81 }