forked from TrenchBoot/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterate_keys.go
50 lines (44 loc) · 1.33 KB
/
iterate_keys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package vals
import (
"errors"
"github.com/u-root/u-root/cmds/core/elvish/hashmap"
)
// KeysIterator wraps the IterateKeys method.
type KeysIterator interface {
// IterateKeys calls the passed function with each key within the receiver.
// The iteration is aborted if the function returns false.
IterateKeys(func(v interface{}) bool)
}
// IterateKeys iterates the keys of the supplied value, calling the supplied
// function for each key. The function can return false to break the iteration.
// It is implemented for the mapKeysIterable type and types satisfying the
// IterateKeyser interface. For these types, it always returns a nil error. For
// other types, it doesn't do anything and returns an error.
func IterateKeys(v interface{}, f func(interface{}) bool) error {
switch v := v.(type) {
case KeysIterator:
v.IterateKeys(f)
case mapKeysIterable:
for it := v.Iterator(); it.HasElem(); it.Next() {
k, _ := it.Elem()
if !f(k) {
break
}
}
default:
return errors.New(Kind(v) + " cannot have its keys iterated")
}
return nil
}
type mapKeysIterable interface {
Iterator() hashmap.Iterator
}
// Feed calls the function with given values, breaking earlier if the function
// returns false.
func Feed(f func(interface{}) bool, values ...interface{}) {
for _, value := range values {
if !f(value) {
break
}
}
}