lib/rambling/trie/branches.rb in rambling-trie-0.5.2 vs lib/rambling/trie/branches.rb in rambling-trie-0.6.0
- old
+ new
@@ -14,49 +14,30 @@
return
end
first_letter = word.slice(0).to_sym
- if children.has_key? first_letter
+ if children_tree.has_key? first_letter
word.slice! 0
- child = children[first_letter]
+ child = children_tree[first_letter]
child << word
child
else
- children[first_letter] = Node.new word, self
+ children_tree[first_letter] = Node.new word, self
end
end
alias_method :<<, :add
protected
- def branch_when_uncompressed?(chars)
- chars.empty? || fulfills_uncompressed_condition?(:branch_when_uncompressed?, chars)
+ def partial_word_when_uncompressed?(chars)
+ chars.empty? || fulfills_uncompressed_condition?(:partial_word_when_uncompressed?, chars)
end
- def branch_when_compressed?(chars)
- return true if chars.empty?
-
- first_letter = chars.slice! 0
- current_key, current_key_string = current_key first_letter
-
- unless current_key.nil?
- return children[current_key].branch_when_compressed?(chars) if current_key_string.length == first_letter.length
-
- while not chars.empty?
- char = chars.slice! 0
-
- break unless current_key_string[first_letter.length] == char
-
- return true if chars.empty?
- first_letter << char
- return children[current_key].branch_when_compressed?(chars) if current_key_string.length == first_letter.length
- end
- end
-
- false
+ def partial_word_when_compressed?(chars)
+ chars.empty? || compressed_trie_has_partial_word?(chars)
end
def word_when_uncompressed?(chars)
(chars.empty? && terminal?) || fulfills_uncompressed_condition?(:word_when_uncompressed?, chars)
end
@@ -66,22 +47,36 @@
first_letter = ''
while not chars.empty?
first_letter << chars.slice!(0)
key = first_letter.to_sym
- return children[key].word_when_compressed?(chars) if children.has_key? key
+ return children_tree[key].word_when_compressed?(chars) if children_tree.has_key? key
end
false
end
private
+ def compressed_trie_has_partial_word?(chars)
+ current_length = 0
+ current_key, current_key_string = current_key chars.slice!(0)
+
+ begin
+ current_length += 1
+
+ if current_key_string.length == current_length || chars.empty?
+ return children_tree[current_key].partial_word_when_compressed?(chars)
+ end
+ end while current_key_string[current_length] == chars.slice!(0)
+ false
+ end
+
def current_key(letter)
current_key_string = current_key = nil
- children.keys.each do |key|
+ children_tree.keys.each do |key|
key_string = key.to_s
if key_string.start_with? letter
current_key = key
current_key_string = key_string
break
@@ -93,10 +88,10 @@
def fulfills_uncompressed_condition?(method, chars)
first_letter = chars.slice! 0
unless first_letter.nil?
first_letter_sym = first_letter.to_sym
- return children[first_letter_sym].send(method, chars) if children.has_key? first_letter_sym
+ return children_tree[first_letter_sym].send(method, chars) if children_tree.has_key? first_letter_sym
end
false
end
end