gitee.com/quant1x/gox@v1.21.2/util/treebidimap/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 treebidimap 6 7 import ( 8 "gitee.com/quant1x/gox/util/internal" 9 ) 10 11 func assertEnumerableImplementation() { 12 var _ internal.EnumerableWithKey = (*Map)(nil) 13 } 14 15 // Each calls the given function once for each element, passing that element's key and value. 16 func (m *Map) Each(f func(key interface{}, value interface{})) { 17 iterator := m.Iterator() 18 for iterator.Next() { 19 f(iterator.Key(), iterator.Value()) 20 } 21 } 22 23 // Map invokes the given function once for each element and returns a container 24 // containing the values returned by the given function as key/value pairs. 25 func (m *Map) Map(f func(key1 interface{}, value1 interface{}) (interface{}, interface{})) *Map { 26 newMap := NewWith(m.keyComparator, m.valueComparator) 27 iterator := m.Iterator() 28 for iterator.Next() { 29 key2, value2 := f(iterator.Key(), iterator.Value()) 30 newMap.Put(key2, value2) 31 } 32 return newMap 33 } 34 35 // Select returns a new container containing all elements for which the given function returns a true value. 36 func (m *Map) Select(f func(key interface{}, value interface{}) bool) *Map { 37 newMap := NewWith(m.keyComparator, m.valueComparator) 38 iterator := m.Iterator() 39 for iterator.Next() { 40 if f(iterator.Key(), iterator.Value()) { 41 newMap.Put(iterator.Key(), iterator.Value()) 42 } 43 } 44 return newMap 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 (m *Map) Any(f func(key interface{}, value interface{}) bool) bool { 50 iterator := m.Iterator() 51 for iterator.Next() { 52 if f(iterator.Key(), 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 (m *Map) All(f func(key interface{}, value interface{}) bool) bool { 62 iterator := m.Iterator() 63 for iterator.Next() { 64 if !f(iterator.Key(), 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 (key,value) for which the function is true or nil,nil otherwise if no element 73 // matches the criteria. 74 func (m *Map) Find(f func(key interface{}, value interface{}) bool) (interface{}, interface{}) { 75 iterator := m.Iterator() 76 for iterator.Next() { 77 if f(iterator.Key(), iterator.Value()) { 78 return iterator.Key(), iterator.Value() 79 } 80 } 81 return nil, nil 82 }