Sha256: 728e24fa9dd6460b911cdc91a6a3850a6f270c20ca2de6a739be7aa67dd5cb19

Contents?: true

Size: 1.1 KB

Versions: 6

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

class Serega
  #
  # Utilities
  #
  module SeregaUtils
    #
    # Duplicates nested hashes and arrays
    #
    class EnumDeepDup
      DUP = {
        Hash => ->(data) { dup_hash_values(data) },
        Array => ->(data) { dup_array_values(data) }
      }.freeze
      private_constant :DUP

      class << self
        #
        # Deeply duplicate provided data
        #
        # @param data [Hash, Array] Data to duplicate
        #
        # @return [Hash, Array] Duplicated data
        #
        def call(data)
          duplicate_data = data.dup
          DUP.fetch(duplicate_data.class).call(duplicate_data)
          duplicate_data
        end

        private

        def dup_hash_values(duplicate_data)
          duplicate_data.each do |key, value|
            duplicate_data[key] = call(value) if value.is_a?(Enumerable)
          end
        end

        def dup_array_values(duplicate_data)
          duplicate_data.each_with_index do |value, index|
            duplicate_data[index] = call(value) if value.is_a?(Enumerable)
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
serega-0.9.0 lib/serega/utils/enum_deep_dup.rb
serega-0.8.3 lib/serega/utils/enum_deep_dup.rb
serega-0.8.2 lib/serega/utils/enum_deep_dup.rb
serega-0.8.1 lib/serega/utils/enum_deep_dup.rb
serega-0.8.0 lib/serega/utils/enum_deep_dup.rb
serega-0.7.0 lib/serega/utils/enum_deep_dup.rb