Sha256: 9a59add5b54b8063520adc0ae05a44b1aa59bde4537ce6026233810f078ade9a

Contents?: true

Size: 1.01 KB

Versions: 5

Compression:

Stored size: 1.01 KB

Contents

module Picky::Optimizers::Memory
  
  # Straightforward implementation of an array deduplicator.
  # Tries to find duplicate instances of Array values in a hash
  # and points references that point to a duplicate to one of the
  # Array instances.
  #
  # TODO Could we have C-Ruby point to parts of another Array?
  #
  class ArrayDeduplicator
    
    def deduplicate hashes, array_references = Hash.new
      hashes.inject(array_references) do |array_references, hash|
        deduplicate_hash hash, array_references
        array_references
      end
    end
    
    def deduplicate_hash hash, array_references
      hash.each do |k, ary|
        stored_ary = if array_references.has_key?(ary)
          array_references.fetch ary
        else
          # Prepare ary for reference cache.
          compact_ary = compact ary
          # Cache ary.
          array_references.store ary, compact_ary
        end
        
        hash[k] = stored_ary
      end
    end
    
    def compact ary
      Array[*ary]
    end
    
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
picky-4.31.3 lib/picky/optimizers/memory/array_deduplicator.rb
picky-4.31.2 lib/picky/optimizers/memory/array_deduplicator.rb
picky-4.31.1 lib/picky/optimizers/memory/array_deduplicator.rb
picky-4.31.0 lib/picky/optimizers/memory/array_deduplicator.rb
picky-4.30.0 lib/picky/optimizers/memory/array_deduplicator.rb