blob: ad0d142510a54821a5a60c7a7fa1eeac0cc9c90c [file] [log] [blame]
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +00001package ordered_map
2
3import (
4 "fmt"
5 "bytes"
6)
7
8type node struct {
9 Prev *node
10 Next *node
11 Value interface{}
12}
13
14func newRootNode() *node {
15 root := &node{}
16 root.Prev = root
17 root.Next = root
18 return root
19}
20
21func newNode(prev *node, next *node, key interface{}) *node {
22 return &node{Prev: prev, Next: next, Value: key}
23}
24
25func (n *node) Add(value string) {
26 root := n
27 last := root.Prev
28 last.Next = newNode(last, n, value)
29 root.Prev = last.Next
30}
31
32func (n *node) String() string {
33 var buffer bytes.Buffer
34 if n.Value == "" {
35 // Need to sentinel
36 var curr *node
37 root := n
38 curr = root.Next
39 for curr != root {
40 buffer.WriteString(fmt.Sprintf("%s, ", curr.Value))
41 curr = curr.Next
42 }
43 } else {
44 // Else, print pointer value
45 buffer.WriteString(fmt.Sprintf("%p, ", &n))
46 }
47 return fmt.Sprintf("LinkList[%v]", buffer.String())
48}
49
50func (n *node) IterFunc() func() (string, bool) {
51 var curr *node
52 root := n
53 curr = root.Next
54 return func() (string, bool) {
55 for curr != root {
56 tmp := curr.Value.(string)
57 curr = curr.Next
58 return tmp, true
59 }
60 return "", false
61 }
62}