Skip to content

Commit

Permalink
feat: add new node method "IndexOrGetWithIdx" (#594)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bisstocuz committed Feb 20, 2024
1 parent 3f15f26 commit eb25ba2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
29 changes: 20 additions & 9 deletions ast/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -851,19 +851,30 @@ func (self *Node) IndexPair(idx int) *Pair {
return self.skipIndexPair(idx)
}

func (self *Node) indexOrGet(idx int, key string) (*Node, int) {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return unwrapError(err), idx
}

pr := self.skipIndexPair(idx)
if pr != nil && pr.Key == key {
return &pr.Value, idx
}

return self.skipKey(key)
}

// IndexOrGet firstly use idx to index a value and check if its key matches
// If not, then use the key to search value
func (self *Node) IndexOrGet(idx int, key string) *Node {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return unwrapError(err)
}
node, _ := self.indexOrGet(idx, key)
return node
}

pr := self.skipIndexPair(idx)
if pr != nil && pr.Key == key {
return &pr.Value
}
n, _ := self.skipKey(key)
return n
// IndexOrGetWithIdx attempts to retrieve a node by index and key, returning the node and its correct index.
// If the key does not match at the given index, it searches by key and returns the node with its updated index.
func (self *Node) IndexOrGetWithIdx(idx int, key string) (*Node, int) {
return self.indexOrGet(idx, key)
}

/** Generic Value Converters **/
Expand Down
11 changes: 11 additions & 0 deletions ast/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,17 @@ func TestIndexOrGet(t *testing.T) {
}
}

func TestIndexOrGetWithIdx(t *testing.T) {
root, _ := NewParser(`{"a":1,"b":2}`).Parse()
b, idx := root.IndexOrGetWithIdx(0, "b")
if v, err := b.Int64(); err != nil || v != int64(2) {
t.Fatal(b, idx)
}
if idx != 1 {
t.Fatal(b, idx)
}
}

func TestTypeCast(t *testing.T) {
type tcase struct {
method string
Expand Down

0 comments on commit eb25ba2

Please sign in to comment.