forked from u-root/u-root
/
iterate.go
61 lines (54 loc) · 1.49 KB
/
iterate.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
51
52
53
54
55
56
57
58
59
60
61
package vals
import (
"errors"
"github.com/u-root/u-root/cmds/core/elvish/vector"
)
// Iterator wraps the Iterate method.
type Iterator interface {
// Iterate calls the passed function with each value within the receiver.
// The iteration is aborted if the function returns false.
Iterate(func(v interface{}) bool)
}
// Iterate iterates the supplied value, and calls the supplied function in each
// of its elements. The function can return false to break the iteration. It is
// implemented for the builtin type string, and types satisfying the
// listIterable or Iterator interface. For these types, it always returns a nil
// error. For other types, it doesn't do anything and returns an error.
func Iterate(v interface{}, f func(interface{}) bool) error {
switch v := v.(type) {
case Iterator:
v.Iterate(f)
case string:
for _, r := range v {
b := f(string(r))
if !b {
break
}
}
case listIterable:
for it := v.Iterator(); it.HasElem(); it.Next() {
if !f(it.Elem()) {
break
}
}
default:
return errors.New(Kind(v) + " cannot be iterated")
}
return nil
}
type listIterable interface {
Iterator() vector.Iterator
}
var _ listIterable = vector.Vector(nil)
// Collect collects all elements of an iterable value into a slice.
func Collect(it interface{}) ([]interface{}, error) {
var vs []interface{}
if len := Len(it); len >= 0 {
vs = make([]interface{}, 0, len)
}
err := Iterate(it, func(v interface{}) bool {
vs = append(vs, v)
return true
})
return vs, err
}