diff --git a/tree/children.go b/tree/children.go index 6727092a..cace8ee1 100644 --- a/tree/children.go +++ b/tree/children.go @@ -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. @@ -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 { diff --git a/tree/tree.go b/tree/tree.go index 4d93670a..2788f2c7 100644 --- a/tree/tree.go +++ b/tree/tree.go @@ -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