Skip to content

Commit

Permalink
Start rendering and testing
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Aug 31, 2024
1 parent 0debd2b commit 076013d
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
25 changes: 25 additions & 0 deletions btree/btree_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package btree

import (
"fmt"
"testing"
)

func intCmp(a, b int) int {
return a - b
}

func TestBasic(t *testing.T) {
bt := NewWithTee[int, string](intCmp, 4)
bt.Insert(2, "two")
bt.Insert(4, "four")
bt.Insert(1, "one")
bt.Insert(7, "seven")
bt.Insert(6, "six")
bt.Insert(3, "three")
bt.Insert(11, "eleven")
bt.Insert(9, "nine")
bt.Insert(21, "twentyone")

fmt.Println(bt.renderDot())
}
53 changes: 53 additions & 0 deletions btree/dot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package btree

import (
"fmt"
"iter"
"strings"
)

const prefix = `digraph g {
node [shape = record,height=0.1];
`

func (bt *BTree[K, V]) renderDot() string {
nodeNames := make(map[*node[K, V]]string)
nodeNumber := 0

node2name := func(n *node[K, V]) string {
if name, ok := nodeNames[n]; ok {
return name
}
nodeNames[n] = fmt.Sprintf("node%d", nodeNumber)
nodeNumber++
return nodeNames[n]
}

// TODO: continue here, emit node contents followed by child pointers
var sb strings.Builder
sb.WriteString(prefix)
for n := range bt.nodesPreOrder() {
sb.WriteString(fmt.Sprintf("%s\n", node2name(n)))
}
sb.WriteString("}\n")

return sb.String()
}

func (bt *BTree[K, V]) nodesPreOrder() iter.Seq[*node[K, V]] {
return func(yield func(*node[K, V]) bool) {
bt.pushPreOrder(yield, bt.root)
}
}

func (bt *BTree[K, V]) pushPreOrder(yield func(*node[K, V]) bool, n *node[K, V]) bool {
if !yield(n) {
return false
}
for _, c := range n.children {
if !bt.pushPreOrder(yield, c) {
return false
}
}
return true
}

0 comments on commit 076013d

Please sign in to comment.