Sha256: e70c6e726f33a33d6ebc1d1078a49370ed6a98205ed3bea5de419c77e78a43cb

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require_relative './repository/hash_repository'
require_relative './repository/active_record_repository'
require_relative './repository/struct_repository'

module HashPivot
  class Table
    # @param [Array<Hash>] data
    def initialize(data, repository: HashPivot::Repository::HashRepository)
      @data = data
      @repository = repository
    end

    # @param [Array, Object] group
    # @param [Object] pivot_in
    # @param [Array] pivot_kinds
    def pivot(group, pivot_in, pivot_kinds, &block)
      group = [group] unless group.is_a?(Array)
      @repository.hash_by_group(@data, group, pivot_in).each_with_object([]) do |(key, array), memo|
        hash = pivot_with_sum(pivot_kinds, array, pivot_in, &block)

        memo << key.merge(hash)
      end
    end

    def pivot_with_sum(pivot_kinds, array, pivot_in, &block)
      pivot_kinds ||= array.map { |h| h[pivot_in] }.uniq.compact
      pivot_kinds.each_with_object({}) do |pivot_kind, memo|
        pivoted_data = array.select { |h| h[pivot_in] == pivot_kind }
        memo[pivot_kind] = if block
                             yield(pivoted_data)
                           else
                             pivoted_data
                           end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hash_pivot-0.2.0 lib/hash_pivot/table.rb
hash_pivot-0.1.0 lib/hash_pivot/table.rb