tree.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // tree project tree.go
  2. // a relativey simple recursive tree with an arbitrary amount of children on each level.
  3. package tree
  4. type Node struct {
  5. Child *Node
  6. After *Node
  7. Before *Node
  8. Parent *Node
  9. Data interface{}
  10. }
  11. func NewEmpty() *Node {
  12. return &Node{}
  13. }
  14. func New(parent *Node, data interface{}) *Node {
  15. node := NewEmpty()
  16. node.Parent = parent
  17. node.Data = data
  18. return node
  19. }
  20. func (me *Node) LastSibling() *Node {
  21. res := me
  22. for res != nil && res.After != nil {
  23. res = res.After
  24. }
  25. return res
  26. }
  27. func (me *Node) InsertSibling(sibling *Node) *Node {
  28. after := me.After
  29. me.After = sibling
  30. sibling.Before = me
  31. sibling.After = after
  32. sibling.Parent = me.Parent
  33. return sibling
  34. }
  35. func (me *Node) AppendSibling(sibling *Node) *Node {
  36. return me.LastSibling().InsertSibling(sibling)
  37. }
  38. func (me *Node) AppendChild(child *Node) *Node {
  39. child.Parent = me
  40. if me.Child == nil {
  41. me.Child = child
  42. } else {
  43. me.Child.AppendSibling(child)
  44. }
  45. return child
  46. }
  47. func (me *Node) NewSibling(data interface{}) *Node {
  48. node := New(me.Parent, data)
  49. return me.AppendSibling(node)
  50. }
  51. func (me *Node) NewChild(data interface{}) *Node {
  52. node := New(me, data)
  53. return me.AppendChild(node)
  54. }
  55. func (me *Node) Walk(walker func(me *Node) *Node) *Node {
  56. node := me
  57. if found := walker(node); found != nil {
  58. return found
  59. }
  60. if me.Child != nil {
  61. if found := me.Child.Walk(walker); found != nil {
  62. return found
  63. }
  64. }
  65. if me.After != nil {
  66. if found := me.After.Walk(walker); found != nil {
  67. return found
  68. }
  69. }
  70. return nil
  71. }