aboutsummaryrefslogtreecommitdiff
path: root/model/array.go
blob: 528f1ef9db0d2a649c46d01f9dd67863e0f09936 (plain) (blame)
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
package model

import "fmt"

// Index returns node by index from array
func (n *Node) Index(idx int) (*Node, error) {
	arrlen := len(n.ArrayValue)
	if idx >= arrlen {
		return nil, fmt.Errorf("index %d out of range (len=%d)", idx, arrlen)
	}
	return n.ArrayValue[idx], nil
}

// SetIndex sets node to array by index
func (n *Node) SetIndex(idx int, value *Node) error {
	arrlen := len(n.ArrayValue)
	if idx >= arrlen {
		return fmt.Errorf("index %d out of range (len=%d)", idx, arrlen)
	}
	n.ArrayValue[idx] = value
	return nil
}

// Each applies callback to each element of array
func (n *Node) Each(cb func(idx int, value *Node) error) error {
	for i, v := range n.ArrayValue {
		if err := cb(i, v); err != nil {
			return err
		}
	}
	return nil
}

// RemoveIndex from array
func (n *Node) RemoveIndex(idx int) error {
	arrlen := len(n.ArrayValue)
	if idx >= arrlen {
		return fmt.Errorf("index %d out of range (len=%d)", idx, arrlen)
	}
	n.ArrayValue = append(n.ArrayValue[:idx], n.ArrayValue[idx:]...)
	return nil
}