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