Last active
July 18, 2018 22:30
-
-
Save danielfoxp2/0ac6a1212bca6d7bbfabea8afdf8a68f to your computer and use it in GitHub Desktop.
Example to flat an nested arrays in Elixir
This file contains hidden or 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 FlatAnything do | |
def flatten([]), do: [] | |
def flatten(this_collection) when is_list(this_collection) do | |
[head | tail] = this_collection | |
flatten(head) ++ flatten(tail) | |
end | |
def flatten(element), do: [element] | |
end |
This file contains hidden or 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 FlatAnythingTest do | |
use ExUnit.Case | |
doctest FlatAnything | |
test "that x became [x]" do | |
assert FlatAnything.flatten(1) == [1] | |
end | |
test "that x as string became [x] with string" do | |
assert FlatAnything.flatten("a") == ["a"] | |
end | |
test "that [x] is flattened to [x]" do | |
assert FlatAnything.flatten([1]) == [1] | |
end | |
test "that [x, y, z] is flattened to [x, y, z]" do | |
assert FlatAnything.flatten([1, 2, 3]) == [1, 2, 3] | |
end | |
test "that [[x]] is flattened to [x]" do | |
assert FlatAnything.flatten([[1]]) == [1] | |
end | |
test "that [[x], y] is flattened to [x, y]" do | |
assert FlatAnything.flatten([[1], 2]) == [1, 2] | |
end | |
test "that [[x], [y]] is flattened to [x, y]" do | |
assert FlatAnything.flatten([[1], [2]]) == [1, 2] | |
end | |
test "that [[[x]], [y]] is flattened to [x, y]" do | |
assert FlatAnything.flatten([[[1]], [2]]) == [1, 2] | |
end | |
test "that [[w, x, [y]], z] is flattened to [w, x, y, z]" do | |
assert FlatAnything.flatten([[1,2,[3]],4]) == [1, 2, 3, 4] | |
end | |
test "that [[w, x, [y, a, b, c]], z] is flattened to [w, x, y, a, b, c, z]" do | |
assert FlatAnything.flatten([[1,2,[3, 4, 5, 6]], 7]) == [1, 2, 3, 4, 5, 6, 7] | |
end | |
test "that [[[w, [x, y]]], [z]] is flattened to [w, x, y, z]" do | |
assert FlatAnything.flatten([[[1, [2, 3]]], [4]]) == [1, 2, 3, 4] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment