Search code examples
crystal-lang

Flatten array in depth one


I try to get one depth flatten method

[ 1, [2], [[3]] ] => [1, 2, [3]]

[ 1, 2, [[3]] ] => [1, 2, [3]]

[[1, [[2, 3]]]] => [1, [[2, 3]]]

[1, 2] => [1, 2]

Update my code to

def flatten(array)
    result = [] of typeof(array) | typeof(array.first)

    array.each do |item|
      if item.is_a?(Array)
        result = ([] of typeof(item) | typeof(item.first)) + result
        result.concat(item)
      else
        result << item
      end
    end

    result
  end

But flatten([1, 2]) Failed to raise an exception https://play.crystal-lang.org/#/r/3p6h

Look https://github.com/crystal-lang/crystal/issues/5805


Solution

  • To be safe you need the union of the array type and its element types:

    def unwrap(array)
      result = [] of typeof(array)|typeof(array.first)
      array.each do |item|
        if item.is_a?(Array)
          result.concat item
        else
          result << item
        end
      end
      result
    end