Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add new node method "IndexOrGetWithIdx" #594

Merged
merged 2 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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