Debian Codegraph @

gopls/internal/util/moremaps/maps.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. 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 moremaps
6
7 import (
8 "cmp"
9 "iter"
10 "maps"
11 "slices"
12 )
13
14 // Arbitrary returns an arbitrary (key, value) entry from the map and ok is true, if
15 // the map is not empty. Otherwise, it returns zero values for K and V, and false.
16 func Arbitrary[K comparable, V any](m map[K]V) (_ K, _ V, ok bool) {
17 for k, v := range m {
18 return k, v, true
19 }
20 return
21 }
22
23 // Group returns a new non-nil map containing the elements of s grouped by the
24 // keys returned from the key func.
25 func Group[K comparable, V any](s []V, key func(V) K) map[K][]V {
26 m := make(map[K][]V)
27 for _, v := range s {
28 k := key(v)
29 m[k] = append(m[k], v)
30 }
31 return m
32 }
33
34 // KeySlice returns the keys of the map M, like slices.Collect(maps.Keys(m)).
35 func KeySlice[M ~map[K]V, K comparable, V any](m M) []K {
36 r := make([]K, 0, len(m))
37 for k := range m {
38 r = append(r, k)
39 }
40 return r
41 }
42
43 // ValueSlice returns the values of the map M, like slices.Collect(maps.Values(m)).
44 func ValueSlice[M ~map[K]V, K comparable, V any](m M) []V {
45 r := make([]V, 0, len(m))
46 for _, v := range m {
47 r = append(r, v)
48 }
49 return r
50 }
51
52 // SameKeys reports whether x and y have equal sets of keys.
53 func SameKeys[K comparable, V1, V2 any](x map[K]V1, y map[K]V2) bool {
54 ignoreValues := func(V1, V2) bool { return true }
55 return maps.EqualFunc(x, y, ignoreValues)
56 }
57
58 // Sorted returns an iterator over the entries of m in key order.
59 func Sorted[M ~map[K]V, K cmp.Ordered, V any](m M) iter.Seq2[K, V] {
60 // TODO(adonovan): use maps.Sorted if proposal #68598 is accepted.
61 return func(yield func(K, V) bool) {
62 keys := KeySlice(m)
63 slices.Sort(keys)
64 for _, k := range keys {
65 if !yield(k, m[k]) {
66 break
67 }
68 }
69 }
70 }
71
72 // SortedFunc returns an iterator over the entries of m in the key order determined by cmp.
73 func SortedFunc[M ~map[K]V, K comparable, V any](m M, cmp func(x, y K) int) iter.Seq2[K, V] {
74 // TODO(adonovan): use maps.SortedFunc if proposal #68598 is accepted.
75 return func(yield func(K, V) bool) {
76 keys := KeySlice(m)
77 slices.SortFunc(keys, cmp)
78 for _, k := range keys {
79 if !yield(k, m[k]) {
80 break
81 }
82 }
83 }
84 }
85
86 // Delete is like delete(m, k) but reports whether deletion occurred.
87 func Delete[M ~map[K]V, K comparable, V any](m M, k K) bool {
88 pre := len(m)
89 delete(m, k)
90 return pre != len(m)
91 }