Skip to content

Commit

Permalink
Add String() to Node struct.
Browse files Browse the repository at this point in the history
  • Loading branch information
q-uint committed Jan 22, 2025
1 parent 4ef7b5e commit 99b4c4b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions parser/node.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package parser

import (
"fmt"
"strings"
)

// Node is a node in the parse tree.
type Node struct {
// Name is the name of the node.
Expand All @@ -10,6 +15,17 @@ type Node struct {
children []*Node
}

func (n *Node) String() string {
if len(n.children) == 0 {
return fmt.Sprintf("{%q: %q}", n.Name, n.value)
}
b := make([]string, len(n.children))
for i, c := range n.children {
b[i] = c.String()
}
return fmt.Sprintf("{%q: [%s]}", n.Name, strings.Join(b, ", "))
}

// NewNode creates a new node.
func NewNode(name, value string) *Node {
return &Node{Name: name, value: value}
Expand Down
15 changes: 15 additions & 0 deletions parser/node_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package parser_test

import (
"fmt"

"github.com/0x51-dev/upeg/parser"
)

func ExampleNode_String() {
a := parser.NewNode("a", "0")
x := parser.NewParentNode("x", []*parser.Node{a})
fmt.Println(x)
// Output:
// {"x": [{"a": "0"}]}
}

0 comments on commit 99b4c4b

Please sign in to comment.