Debian Codegraph @

helpers/tdutil/map.go

raw
1 // Copyright (c) 2018, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package tdutil
8
9 import (
10 "reflect"
11 "sort"
12
13 tdsort "github.com/maxatome/go-testdeep/internal/sort"
14 )
15
16 // MapSortedKeys returns a slice of all sorted keys of map m. It
17 // panics if m's [reflect.Kind] is not [reflect.Map].
18 func MapSortedKeys(m reflect.Value) []reflect.Value {
19 ks := m.MapKeys()
20 sort.Sort(tdsort.Values(ks))
21 return ks
22 }
23
24 // MapEach calls fn for each key/value pair of map m. If fn
25 // returns false, it will not be called again.
26 // MapEach returns false if fn returned false.
27 func MapEach(m reflect.Value, fn func(k, v reflect.Value) bool) bool {
28 return tdsort.MapEach(m, fn)
29 }
30
31 // MapEachValue calls fn for each value of map m. If fn returns
32 // false, it will not be called again.
33 // MapEachValue returns false if fn returned false.
34 func MapEachValue(m reflect.Value, fn func(k reflect.Value) bool) bool {
35 iter := m.MapRange()
36 for iter.Next() {
37 if !fn(iter.Value()) {
38 return false
39 }
40 }
41 return true
42 }
43
44 // MapSortedValues returns a slice of all sorted values of map m. It
45 // panics if m's [reflect.Kind] is not [reflect.Map].
46 func MapSortedValues(m reflect.Value) []reflect.Value {
47 vs := make([]reflect.Value, 0, m.Len())
48 iter := m.MapRange()
49 for iter.Next() {
50 vs = append(vs, iter.Value())
51 }
52 sort.Sort(tdsort.Values(vs))
53 return vs
54 }