Created
July 2, 2019 22:51
-
-
Save pietrofxq/4612b5c3c4e22e4b5e022f17fc79051b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Flatten do | |
@moduledoc """ | |
Documentation for Flatten. | |
""" | |
@doc """ | |
Flatten an array. Ignore nil and empty list values | |
## Examples | |
iex> Flatten.flatten([1, 2, [3], [4, 5, [6, 7, 8, [9, 10]]]]) | |
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
""" | |
@spec flatten(list(integer)) :: list(integer) | |
def flatten(list), do: flatten(list, []) | |
defp flatten([head | tail], acc) when is_nil(head) or head == [], do: flatten(tail, acc) | |
defp flatten([head | tail], acc) when is_list(head), do: flatten(head, flatten(tail, acc)) | |
defp flatten([head | tail], acc), do: [head | flatten(tail, acc)] | |
defp flatten([], acc), do: acc | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule FlattenTest do | |
use ExUnit.Case | |
doctest Flatten | |
test "flattens array" do | |
assert Flatten.flatten([[1, 2, [3]], 4]) == Enum.to_list(1..4) | |
end | |
test "empty list returns empty list" do | |
assert Flatten.flatten([]) == [] | |
end | |
test "ignores empty list and nil values" do | |
assert Flatten.flatten([nil, [], [], nil, 1]) == [1] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment