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