Skip to content

Commit

Permalink
Implement AddKeysFromFile()
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Erin and Derek Parker authored and hashrocketeer committed Mar 6, 2014
1 parent 04b1f59 commit 9146713
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
3 changes: 3 additions & 0 deletions fixtures/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
foo
bar
baz
30 changes: 30 additions & 0 deletions trie.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
package trie

import (
"bufio"
"io"
"log"
"os"
"strings"
)

// Implementation of an R-Way Trie data structure.
//
// A Trie has a root Node which is the base of the tree.
Expand Down Expand Up @@ -62,6 +70,28 @@ func (t *Trie) AddKey(key string) int {
return t.addrune(t.Root(), runes, 0)
}

func (t *Trie) AddKeysFromFile(path string) {
file, err := os.Open(path)
if err != nil {
log.Fatal(err)
}

reader := bufio.NewReader(file)

for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
log.Fatal(err)
}

line = strings.TrimSuffix(line, "\n")
t.AddKey(line)
}
}

func (t *Trie) Keys() []string {
return t.KeysWithPrefix("")
}
Expand Down
20 changes: 20 additions & 0 deletions trie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,26 @@ func TestTrieAdd(t *testing.T) {
}
}

func TestTrieAddFromFile(t *testing.T) {
path := "fixtures/test.txt"
expected := []string{"foo", "bar", "baz"}

trie := CreateTrie()
trie.AddKeysFromFile(path)
keys := trie.Keys()

kl := len(keys)
if kl != 3 {
t.Errorf("Expected 3 keys, got %d, keys were: %v", kl, trie.Keys())
}

for i, key := range keys {
if key != expected[i] {
t.Errorf("Expected %#v, got %#v", expected[i], key)
}
}
}

func TestTrieKeys(t *testing.T) {
trie := CreateTrie()
expected := []string{"bar", "foo"}
Expand Down

0 comments on commit 9146713

Please sign in to comment.