lib/rambling/trie/compressor.rb in rambling-trie-0.8.1 vs lib/rambling/trie/compressor.rb in rambling-trie-0.9.0

- old
+ new

@@ -1,48 +1,47 @@ module Rambling module Trie - # 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 && parent.compressed? + # Responsible for the compression process of a Trie data structure. + class Compressor + # Compresses a node from a Trie data structure. + # @param [RawNode] node the node to compress + # @return [CompressedNode] node the compressed version of the node + def compress node, parent = nil + if node.compressable? + merge_node_with_compressed_child node, parent + else + copy_node_and_compress_children node, parent + end end - # Compress the current node using redundant node elimination. - # @return [Root, Node] the compressed node. - def compress_tree! - if compressable? - merge_with! children.first - compress_tree! - end + private - children.each &:compress_tree! + def merge_node_with_compressed_child node, parent + compressed_child = compress node.children.first - self - end + new_node = Rambling::Trie::CompressedNode.new parent + new_node.letter = node.letter.to_s << compressed_child.letter.to_s + new_node.terminal! if compressed_child.terminal? + new_node.children_tree = compressed_child.children_tree - private + new_node.children.each do |child| + child.parent = new_node + end - def compressable? - !(root? || terminal?) && children_tree.size == 1 + new_node end - def merge_with! child - delete_old_key_on_parent! - redefine_self! child + def copy_node_and_compress_children node, parent + new_node = Rambling::Trie::CompressedNode.new parent - children.each { |node| node.parent = self } - end + new_node.letter = node.letter + new_node.terminal! if node.terminal? - def delete_old_key_on_parent! - parent.delete letter if parent - end + node.children.map do |child| + compress child, new_node + end - def redefine_self! merged_node - self.letter = letter.to_s << merged_node.letter.to_s - self.children_tree = merged_node.children_tree - self.terminal = merged_node.terminal? + new_node end end end end