Skip to content

Instantly share code, notes, and snippets.

@danielfoxp2
Last active July 18, 2018 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielfoxp2/0ac6a1212bca6d7bbfabea8afdf8a68f to your computer and use it in GitHub Desktop.
Save danielfoxp2/0ac6a1212bca6d7bbfabea8afdf8a68f to your computer and use it in GitHub Desktop.
Example to flat an nested arrays in Elixir
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
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