lib/rambling/trie/compressor.rb in rambling-trie-0.5.1 vs lib/rambling/trie/compressor.rb in rambling-trie-0.5.2

- old
+ new

@@ -3,17 +3,17 @@ # Provides the compressing behavior for the Trie data structure. module Compressor # Flag for compressed tries. # @return [Boolean] `true` for compressed tries, `false` otherwise. def compressed? - parent and parent.compressed? + parent && parent.compressed? end # Compress the current node using redundant node elimination. # @return [Root, Node] the compressed node. def compress_tree! - if children.size == 1 and not terminal? and letter + if children.size == 1 && !terminal? && letter merge_with! children.values.first compress_tree! end children.values.each &:compress_tree! @@ -22,26 +22,23 @@ end private def merge_with!(child) - new_letter = (letter.to_s << child.letter.to_s).to_sym + delete_old_key_on_parent! + redefine_self! child - rehash_on_parent! letter, new_letter - redefine_self! new_letter, child - - children.values.each { |node| node.parent = self } + children.each { |_, node| node.parent = self } end - def rehash_on_parent!(old_letter, new_letter) + def delete_old_key_on_parent! return if parent.nil? - parent.delete old_letter - parent[new_letter] = self + parent.delete letter end - def redefine_self!(new_letter, merged_node) - self.letter = new_letter + def redefine_self!(merged_node) + self.letter = letter.to_s << merged_node.letter.to_s self.children = merged_node.children self.terminal = merged_node.terminal? end end end