Skip to content

Commit

Permalink
Fix trie Keys method
Browse files Browse the repository at this point in the history
Fixes #20
  • Loading branch information
zyedidia committed Jun 6, 2022
1 parent 7fb5054 commit e61ed1b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
3 changes: 0 additions & 3 deletions trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,5 @@ func (t *Trie[V]) collect(x *node[V], prefix string, queue []string) []string {
queue = append(queue, prefix+string(x.c))
}
queue = t.collect(x.mid, prefix+string(x.c), queue)
if len(prefix) > 0 {
prefix = prefix[:len(prefix)-1]
}
return t.collect(x.right, prefix, queue)
}
21 changes: 21 additions & 0 deletions trie/trie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package trie_test
import (
"fmt"
"math/rand"
"sort"
"testing"

"github.com/zyedidia/generic/trie"
Expand All @@ -19,7 +20,9 @@ func randstring(n int) string {
}

func checkeq(tr *trie.Trie[int], m map[string]int, t *testing.T) {
keys := make([]string, 0, len(m))
for k, v := range m {
keys = append(keys, k)
tv, ok := tr.Get(k)
if !ok {
t.Fatalf("%v should exist", k)
Expand All @@ -28,6 +31,13 @@ func checkeq(tr *trie.Trie[int], m map[string]int, t *testing.T) {
t.Fatalf("%v != %v, key: %v", tv, v, k)
}
}
trieKeys := tr.Keys()
sort.Strings(keys)
for i := range keys {
if keys[i] != trieKeys[i] {
t.Fatalf("%d, %s != %s", i, keys, trieKeys)
}
}
}

func TestCrossCheck(t *testing.T) {
Expand Down Expand Up @@ -59,6 +69,17 @@ func TestCrossCheck(t *testing.T) {
}
}

func TestKeys(t *testing.T) {
tr := trie.New[int]()
tr.Put("topic1", 1)
tr.Put("topic2", 2)

keys := tr.Keys()
if len(keys) != 2 || keys[0] != "topic1" || keys[1] != "topic2" {
t.Fatal(keys)
}
}

func Example() {
tr := trie.New[int]()
tr.Put("foo", 1)
Expand Down

0 comments on commit e61ed1b

Please sign in to comment.