-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patharray.go
60 lines (50 loc) · 1.07 KB
/
array.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
package jsonast
import (
"errors"
"fmt"
)
var errNotAnArray = errors.New("not an array")
type errIndexOutOfBounds struct {
i int
}
func (e errIndexOutOfBounds) Error() string {
return fmt.Sprintf("index %d is out of bounds", e.i)
}
// Array is an array JSON value
type Array interface {
Value
// Elts returns all of the elements in the array
Elts() []Value
// Foreach executes fn on each Value in Elts()
Foreach(fn func(Value) error) error
// At returns the Value at the given index i. Returns nil and
// an appropriate error if len(Elts()) >= i
At(i int) (Value, error)
}
type arrayImpl struct {
Value
arr []Value
}
func newArray(elts []Value) Array {
return arrayImpl{
Value: valueImpl{isArray: true},
arr: elts,
}
}
func (v arrayImpl) Elts() []Value {
return v.arr
}
func (v arrayImpl) Foreach(fn func(Value) error) error {
for _, val := range v.arr {
if err := fn(val); err != nil {
return err
}
}
return nil
}
func (v arrayImpl) At(i int) (Value, error) {
if i >= len(v.arr) {
return nil, errIndexOutOfBounds{i: i}
}
return v.arr[i], nil
}