Sha256: c036ca58050a663a2ba3576dfd8ef704b406c19d9e5f7ed68d187e617f112dc8

Contents?: true

Size: 1.23 KB

Versions: 29

Compression:

Stored size: 1.23 KB

Contents

module UniverseCompiler
  module Utils

    module DeepTraverse

      def deep_traverse(structure, &block)
        case structure
        when Hash
          deep_traverse_hash structure, &block
        when Array
          deep_traverse_array structure, &block
        else
          yield structure
        end
      end

      def deep_map(structure, &block)
        case structure
        when Hash
          deep_map_hash structure, &block
        when Array
          deep_map_array structure, &block
        else
          yield structure
        end
      end

      private

      def deep_traverse_hash(hash, &block)
        hash.each do |k, v|
          deep_traverse k, &block
          deep_traverse v, &block
        end
      end

      def deep_traverse_array(array, &block)
        array.each.with_index do |v, idx|
          deep_traverse v, &block
        end
      end

      def deep_map_hash(hash, res = {}, &block)
        hash.each do |k, v|
          k = deep_map k, &block
          res[k] = deep_map v, &block
        end
        res
      end

      def deep_map_array(array, res = [], &block)
        array.each.with_index do |v, idx|
          res[idx] = deep_map v, &block
        end
        res
      end

    end

  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
universe_compiler-0.3.2 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.3.1 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.3.0 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.16 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.15 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.14 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.13 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.12 lib/universe_compiler/utils/deep_traverse.rb
universe_compiler-0.2.11 lib/universe_compiler/utils/deep_traverse.rb