Skip to content

Commit

Permalink
Added a method to return early when all elements contained in tree ha…
Browse files Browse the repository at this point in the history
…ve been sent

This can make scenarios where all elements match the query significantly more efficient.
  • Loading branch information
seppestas committed Apr 30, 2015
1 parent c2e6f26 commit 73f3e17
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions stree.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,20 @@ type node struct {
}

type Tree struct {
base []interval
root *node
base []interval
elements map[interface{}]struct{}
root *node
}

// Push pushes an interval to the interval stack
func (t *Tree) Push(from, to int, element interface{}) {
if to < from {
from, to = to, from
}
if t.elements == nil {
t.elements = make(map[interface{}]struct{})
}
t.elements[element] = struct{}{}
t.base = append(t.base, interval{segment{from, to}, element})
}

Expand Down Expand Up @@ -181,16 +186,21 @@ func (t *Tree) QueryIndex(index int) (<-chan interface{}, error) {
elements := make(chan interface{})

go func(intervals chan *interval, elements chan interface{}) {
defer close(elements)
results := make(map[interface{}]struct{})
for interval := range intervals {
_, alreadyFound := results[interval.element]
if !alreadyFound {
// Store an empty struct in the map to minimize memory footprint
results[interval.element] = struct{}{}
elements <- interval.element
if len(results) >= len(t.elements) {
// found all elements that can be found
return
}
}

}
close(elements)
}(intervals, elements)

return elements, nil
Expand All @@ -212,5 +222,4 @@ func query(node *node, index int, results chan<- *interval) {
query(node.right, index, results)
}
}

}

0 comments on commit 73f3e17

Please sign in to comment.