Class: TrieFile::Trie

Inherits:
Object
  • Object
show all
Defined in:
lib/trie-file/trie.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root = nil, hash_mode = :none) ⇒ Trie

Returns a new instance of Trie.



10
11
12
13
# File 'lib/trie-file/trie.rb', line 10

def initialize(root = nil, hash_mode = :none)
  @root = root || Node.new
  @hash_mode = hash_mode
end

Instance Attribute Details

#hash_modeObject (readonly)

Returns the value of attribute hash_mode.



8
9
10
# File 'lib/trie-file/trie.rb', line 8

def hash_mode
  @hash_mode
end

#rootObject (readonly)

Returns the value of attribute root.



8
9
10
# File 'lib/trie-file/trie.rb', line 8

def root
  @root
end

Class Method Details

.hash_key(key, hash_mode) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/trie-file/trie.rb', line 43

def self.hash_key(key, hash_mode)
  case hash_mode
    when :md5
      Digest::MD5.hexdigest(key)
    when :sha1
      Digest::SHA1.hexdigest(key)
    else
      key
  end
end

Instance Method Details

#add(str, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/trie-file/trie.rb', line 15

def add(str, value)
  node = root
  key = hash_key(str)

  key.each_char do |char|
    if node.has_child?(char)
      node = node.child_at(char)
    else
      node = node.add_child(char, Node.new)
    end
  end

  node.value = value
end

#find(key) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/trie-file/trie.rb', line 30

def find(key)
  node = root
  hash_key(key).each_char do |char|
    node = node.child_at(char)
    return nil unless node
  end
  node.value
end

#hash_key(key) ⇒ Object



39
40
41
# File 'lib/trie-file/trie.rb', line 39

def hash_key(key)
  self.class.hash_key(key, hash_mode)
end