Debian Codegraph @

maps/treemap/enumerable.go

raw symbols SCIP
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 treemap
6
7 import (
8 "github.com/emirpasic/gods/v2/containers"
9 rbt "github.com/emirpasic/gods/v2/trees/redblacktree"
10 )
11
12 // Assert Enumerable implementation
13 var _ containers.EnumerableWithKey[string, int] = (*Map[string, int])(nil)
14
15 // Each calls the given function once for each element, passing that element's key and value.
16 func (m *Map[K, V]) Each(f func(key K, value V)) {
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[K, V]) Map(f func(key1 K, value1 V) (K, V)) *Map[K, V] {
26 newMap := &Map[K, V]{tree: rbt.NewWith[K, V](m.tree.Comparator)}
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[K, V]) Select(f func(key K, value V) bool) *Map[K, V] {
37 newMap := &Map[K, V]{tree: rbt.NewWith[K, V](m.tree.Comparator)}
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[K, V]) Any(f func(key K, value V) 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[K, V]) All(f func(key K, value V) 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[K, V]) Find(f func(key K, value V) bool) (k K, v V) {
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 k, v
82 }