Skip to content

Commit

Permalink
feat(tree): add options to modify Tree Nodes after creation
Browse files Browse the repository at this point in the history
  • Loading branch information
bashbunni committed Jan 10, 2025
1 parent 7f1d944 commit 0502e1f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
18 changes: 18 additions & 0 deletions tree/children.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package tree

import "slices"

// Children is the interface that wraps the basic methods of a tree model.
type Children interface {
// At returns the content item of the given index.
Expand All @@ -18,6 +20,22 @@ func (n NodeChildren) Append(child Node) NodeChildren {
return n
}

// Insert inserts a child to the list at the given index.
func (n NodeChildren) Insert(index int, child Node) NodeChildren {
if index < 0 || len(n) < index+1 {
return n
}
return slices.Insert(n, index, child)
}

// Replace swaps the child at the given index with the given child.
func (n NodeChildren) Replace(index int, child Node) NodeChildren {
if index < 0 || len(n) < index+1 {
return n
}
return slices.Replace(n, index, index, child)
}

// Remove removes a child from the list at the given index.
func (n NodeChildren) Remove(index int) NodeChildren {
if index < 0 || len(n) < index+1 {
Expand Down
6 changes: 6 additions & 0 deletions tree/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ func (t *Tree) String() string {
return t.ensureRenderer().render(t, true, "")
}

// SetChildren overwrites a Tree's Children.
func (t *Tree) SetChildren(children ...any) *Tree {
t.children = NodeChildren(nil)
return t.Child(children)
}

// Child adds a child to this Tree.
//
// If a Child Tree is passed without a root, it will be parented to it's sibling
Expand Down

0 comments on commit 0502e1f

Please sign in to comment.