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