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
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