Skip to content

Commit

Permalink
- btree Keys() and Values() implemented with tests (using iterator)
Browse files Browse the repository at this point in the history
  • Loading branch information
emirpasic committed Jul 12, 2016
1 parent 5389805 commit eb4171f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
14 changes: 12 additions & 2 deletions trees/btree/btree.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,22 @@ func (tree *Tree) Size() int {

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
return nil // TODO
keys := make([]interface{}, tree.size)
it := tree.Iterator()
for i := 0; it.Next(); i++ {
keys[i] = it.Key()
}
return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
return nil // TODO
values := make([]interface{}, tree.size)
it := tree.Iterator()
for i := 0; it.Next(); i++ {
values[i] = it.Value()
}
return values
}

// Clear removes all nodes from the tree.
Expand Down
23 changes: 22 additions & 1 deletion trees/btree/btree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package btree

import (
_ "fmt"
"fmt"
"testing"
)

Expand Down Expand Up @@ -384,6 +384,27 @@ func TestBTreeLeftAndRight(t *testing.T) {
}
}

func TestBTreeIteratorValuesAndKeys(t *testing.T) {
tree := NewWithIntComparator(4)
tree.Put(4, "d")
tree.Put(5, "e")
tree.Put(6, "f")
tree.Put(3, "c")
tree.Put(1, "a")
tree.Put(7, "g")
tree.Put(2, "b")
tree.Put(1, "x") // override
if actualValue, expectedValue := fmt.Sprintf("%d%d%d%d%d%d%d", tree.Keys()...), "1234567"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
if actualValue, expectedValue := fmt.Sprintf("%s%s%s%s%s%s%s", tree.Values()...), "xbcdefg"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
if actualValue := tree.Size(); actualValue != 7 {
t.Errorf("Got %v expected %v", actualValue, 7)
}
}

func TestBTreeIteratorNextOnEmpty(t *testing.T) {
tree := NewWithIntComparator(3)
it := tree.Iterator()
Expand Down

0 comments on commit eb4171f

Please sign in to comment.