-
Notifications
You must be signed in to change notification settings - Fork 7
/
walki.go
71 lines (64 loc) · 1.5 KB
/
walki.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) 2020, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
This file provides basic tree walking functions for iterative traversal
of the tree in up / down directions. As compared to the core Func methods,
these are for more dynamic, piecemeal processing.
*/
package ki
// Last returns the last node in the tree
func Last(nd Ki) Ki {
nd = LastChild(nd)
last := nd
nd.WalkPre(func(k Ki) bool {
last = k
return Continue
})
return last
}
// LastChild returns the last child under given node, or node itself if no children
func LastChild(nd Ki) Ki {
if nd.HasChildren() {
ek, err := nd.Children().ElemFromEndTry(0)
if err == nil {
return LastChild(ek)
}
}
return nd
}
// Prev returns previous node in the tree -- nil if top
func Prev(nd Ki) Ki {
if nd.Parent() == nil {
return nil
}
myidx, ok := nd.IndexInParent()
if ok && myidx > 0 {
nn := nd.Parent().Child(myidx - 1)
return LastChild(nn)
}
return nd.Parent()
}
// Next returns next node in the tree, nil if end
func Next(nd Ki) Ki {
if !nd.HasChildren() {
return NextSibling(nd)
}
if nd.HasChildren() {
return nd.Child(0)
}
return nil
}
// NextSibling returns next sibling or nil if none
func NextSibling(nd Ki) Ki {
if nd.Parent() == nil {
return nil
}
myidx, ok := nd.IndexInParent()
if ok {
if myidx < nd.Parent().NumChildren()-1 {
return nd.Parent().Child(myidx + 1)
}
}
return NextSibling(nd.Parent())
}