Skip to content

Commit

Permalink
fix counting algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
256dpi committed Sep 7, 2018
1 parent 3986370 commit eae2eef
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
11 changes: 7 additions & 4 deletions topic/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,17 +364,20 @@ func (t *Tree) Count() int {
t.mutex.RLock()
defer t.mutex.RUnlock()

return t.count(0, t.root)
return t.count(t.root)
}

func (t *Tree) count(counter int, node *node) int {
func (t *Tree) count(node *node) int {
// prepare total
total := 0

// add children to results
for _, child := range node.children {
counter += t.count(counter, child)
total += t.count(child)
}

// add values to result
return counter + len(node.values)
return total + len(node.values)
}

// All will return all stored values in the tree.
Expand Down
3 changes: 2 additions & 1 deletion topic/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,9 @@ func TestTreeCount(t *testing.T) {
tree.Add("foo/bar", 2)
tree.Add("foo/bar/baz", 3)
tree.Add("foo/bar/baz", 4)
tree.Add("quz/bar/baz", 4)

assert.Equal(t, 4, tree.Count())
assert.Equal(t, 5, tree.Count())
}

func TestTreeAll(t *testing.T) {
Expand Down

0 comments on commit eae2eef

Please sign in to comment.