Skip to content

Commit c8b510e

Browse files
authored
Build node (#13)
* Improve Node ID handling * Separate node and tree packages
1 parent 1cb180c commit c8b510e

File tree

6 files changed

+147
-267
lines changed

6 files changed

+147
-267
lines changed

cmd/main.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
"github.com/johnfercher/go-tree/node"
56

67
"github.com/johnfercher/go-tree/tree"
78
)
@@ -10,16 +11,16 @@ import (
1011
func main() {
1112
tr := tree.New[string]()
1213

13-
tr.AddRoot(tree.NewNodeWithID(0, "0.0"))
14+
tr.AddRoot(node.New("0.0").WithID(0))
1415

15-
tr.Add(0, tree.NewNodeWithID(1, "0.1"))
16-
tr.Add(0, tree.NewNodeWithID(2, "0.2"))
16+
tr.Add(0, node.New("0.1").WithID(1))
17+
tr.Add(0, node.New("0.2").WithID(2))
1718

18-
tr.Add(1, tree.NewNodeWithID(3, "1.3"))
19-
tr.Add(1, tree.NewNodeWithID(4, "1.4"))
19+
tr.Add(1, node.New("1.3").WithID(3))
20+
tr.Add(1, node.New("1.4").WithID(4))
2021

21-
tr.Add(2, tree.NewNodeWithID(5, "2.5"))
22-
tr.Add(2, tree.NewNodeWithID(6, "2.6"))
22+
tr.Add(2, node.New("2.5").WithID(5))
23+
tr.Add(2, node.New("2.6").WithID(6))
2324

2425
root, ok := tr.GetRoot()
2526
fmt.Println(ok) // true

tree/node.go renamed to node/node.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package tree
1+
package node
22

33
import (
44
"fmt"
@@ -13,19 +13,17 @@ type Node[T any] struct {
1313
nexts []*Node[T]
1414
}
1515

16-
// NewNode creates a new node.
17-
func NewNode[T any](data T) *Node[T] {
16+
// New creates a new node.
17+
func New[T any](data T) *Node[T] {
1818
return &Node[T]{
1919
data: data,
2020
}
2121
}
2222

23-
// NewNodeWithID creates a new node with ID.
24-
func NewNodeWithID[T any](id int, data T) *Node[T] {
25-
return &Node[T]{
26-
id: id,
27-
data: data,
28-
}
23+
// WithID retrieves data from node.
24+
func (n *Node[T]) WithID(id int) *Node[T] {
25+
n.id = id
26+
return n
2927
}
3028

3129
// GetData retrieves data from node.

0 commit comments

Comments
 (0)