Sha256: 6f4d128f0b44f2c39caccff292b383664d263fa612535b6d36410b4ea90c65fa

Contents?: true

Size: 784 Bytes

Versions: 142

Compression:

Stored size: 784 Bytes

Contents

# frozen_string_literal: true

# A decorator for handling a collection of hashes with similar keys.
#
class HashCollection < SimpleDelegator
  alias_method :collection, :__getobj__

  # Example:
  #
  #   foo = [
  #     {a: 1, b: 2},
  #     {b: 3, c: 4}
  #   ]
  #
  #   bar = HashCollection.new(foo)
  #   bar.to_a => [[:a, 1, nil], [:b, 2, 3], [:c, nil, 4]]
  #
  def to_a
    keys = find_unique_keys
    build_items(keys)
  end

  private

  def find_unique_keys
    collection.flat_map(&:keys).uniq
  end

  def build_items(keys)
    keys.each_with_object([]) do |key, memo|
      memo << build_item_for_key(key)
    end
  end

  def build_item_for_key(key)
    [key] + find_values(key)
  end

  def find_values(key)
    collection.map { |result| result.fetch(key) }
  end
end

Version data entries

142 entries across 142 versions & 1 rubygems

Version Path
renalware-core-2.1.1 lib/hash_collection.rb
renalware-core-2.1.0 lib/hash_collection.rb
renalware-core-2.0.167 lib/hash_collection.rb
renalware-core-2.0.166 lib/hash_collection.rb
renalware-core-2.0.165 lib/hash_collection.rb
renalware-core-2.0.164 lib/hash_collection.rb
renalware-core-2.0.163 lib/hash_collection.rb
renalware-core-2.0.162 lib/hash_collection.rb
renalware-core-2.0.161 lib/hash_collection.rb
renalware-core-2.0.160 lib/hash_collection.rb
renalware-core-2.0.159 lib/hash_collection.rb
renalware-core-2.0.158 lib/hash_collection.rb
renalware-core-2.0.157 lib/hash_collection.rb
renalware-core-2.0.156 lib/hash_collection.rb
renalware-core-2.0.155 lib/hash_collection.rb
renalware-core-2.0.153 lib/hash_collection.rb
renalware-core-2.0.152 lib/hash_collection.rb
renalware-core-2.0.151 lib/hash_collection.rb
renalware-core-2.0.149 lib/hash_collection.rb
renalware-core-2.0.148 lib/hash_collection.rb