Created
November 4, 2018 00:43
-
-
Save joseph-lozano/e8fc2aaf3b419901e35cf288f73fccd8 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 | |
@spec flatten(List.t()) :: List.t() | |
def flatten([]), do: [] | |
def flatten([head | tail]) when is_list(head), do: flatten(head) ++ flatten(tail) | |
def flatten([head | tail]), do: [head | flatten(tail)] | |
def flatten(_), do: raise("argument must be a list") | |
end | |
ExUnit.start() | |
defmodule FlattenTest do | |
import Flatten | |
import ExUnit.Assertions, only: [assert_raise: 2] | |
use ExUnit.Case | |
test "returns an empty array" do | |
assert flatten([]) == [] | |
end | |
test "returns an array of one element" do | |
assert flatten(["a"]) == ["a"] | |
end | |
test "returns an array of two elements" do | |
assert flatten(["a", "b"]) == ["a", "b"] | |
end | |
test "can flatten one element" do | |
assert flatten([["a"]]) == ["a"] | |
end | |
test "raises on non list argument" do | |
assert_raise RuntimeError, fn -> flatten("foo") end | |
end | |
test "big lists work too" do | |
assert flatten([[1, 2, 3], [4, [[5, 6], [7], 8]], 9, 10, [[[[[11]]]]]]) == Enum.to_list(1..11) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment