Skip to content

Commit

Permalink
added get method to tree
Browse files Browse the repository at this point in the history
  • Loading branch information
256dpi committed Nov 3, 2017
1 parent 613f2ad commit 39b59e5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
24 changes: 24 additions & 0 deletions tools/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,30 @@ func (t *Tree) set(value interface{}, i int, segments []string, node *node) {
t.set(value, i+1, segments, child)
}

// Get gets the values from the topic that exactly matches the supplied topics.
func (t *Tree) Get(topic string) []interface{} {
t.mutex.Lock()
defer t.mutex.Unlock()

return t.get(0, strings.Split(topic, t.Separator), t.root)
}

func (t *Tree) get(i int, segments []string, node *node) []interface{} {
// set value on leaf
if i == len(segments) {
return node.values
}

// get next segment
segment := segments[i]
child, ok := node.children[segment]
if !ok {
return nil
}

return t.get(i+1, segments, child)
}

// Remove un-registers the value from the supplied topic. This function will
// automatically shrink the tree.
func (t *Tree) Remove(topic string, value interface{}) {
Expand Down
24 changes: 24 additions & 0 deletions tools/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ func TestTreeSetReplace(t *testing.T) {
assert.Equal(t, 2, tree.root.children["foo"].children["bar"].values[0])
}

func TestTreeGet(t *testing.T) {
tree := NewTree()

tree.Set("foo/#", 1)

assert.Equal(t, 1, tree.Get("foo/#")[0])
}

func TestTreeRemove(t *testing.T) {
tree := NewTree()

Expand Down Expand Up @@ -119,6 +127,14 @@ func TestTreeMatchWildcard4(t *testing.T) {
assert.Equal(t, 1, tree.Match("foo/bar")[0])
}

func TestTreeMatchWildcard5(t *testing.T) {
tree := NewTree()

tree.Add("foo/#", 1)

assert.Equal(t, 1, tree.Match("foo/bar/#")[0])
}

func TestTreeMatchMultiple(t *testing.T) {
tree := NewTree()

Expand Down Expand Up @@ -195,6 +211,14 @@ func TestTreeSearchWildcard4(t *testing.T) {
assert.Equal(t, 1, tree.Search("foo/bar/#")[0])
}

func TestTreeSearchWildcard5(t *testing.T) {
tree := NewTree()

tree.Add("foo/bar/#", 1)

assert.Equal(t, 1, tree.Search("foo/#")[0])
}

func TestTreeSearchMultiple(t *testing.T) {
tree := NewTree()

Expand Down

0 comments on commit 39b59e5

Please sign in to comment.