Class: Picky::Optimizers::Memory::ArrayDeduplicator

Inherits:
Object
  • Object
show all
Defined in:
lib/picky/optimizers/memory/array_deduplicator.rb

Overview

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?

Instance Method Summary collapse

Instance Method Details

#compact(ary) ⇒ Object



34
35
36
# File 'lib/picky/optimizers/memory/array_deduplicator.rb', line 34

def compact ary
  Array[*ary]
end

#deduplicate(hashes, array_references = Hash.new) ⇒ Object



12
13
14
15
16
17
# File 'lib/picky/optimizers/memory/array_deduplicator.rb', line 12

def deduplicate hashes, array_references = Hash.new
  hashes.inject(array_references) do |array_references, hash|
    deduplicate_hash hash, array_references
    array_references
  end
end

#deduplicate_hash(hash, array_references) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/picky/optimizers/memory/array_deduplicator.rb', line 19

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