A curated collection of useful Elixir snippets that you can understand in 30 seconds or less.
Note: This project is inspired by 30 Seconds Of Code, but there's no affiliation of any kind with that project.
✨ Always work in progress ✨
View contents
Check if all the elements in an array are equal.
def all_equal(arr), do: arr |> Enum.dedup() |> Enum.count() == 1
Examples
all_equal([1, 2, 3, 4, 5, 6]) # false
all_equal([1, 1, 1]) # true
Converts a 2D array to a comma-separated values (CSV) string.
def array_to_csv(arr), do: arr |> Enum.join(",")
Examples
array_to_csv([1, 2, 3, 4]) # "1,2,3,4"
Splits values into two groups. If an element in filter is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
def bifurcate(arr, predicate) do
Enum.reduce(
arr,
%{a: [], b: []},
fn x, ac ->
if (predicate.(x)) do
%{a: [x] ++ ac[:a], b: ac[:b]}
else
%{a: ac[:a], b: [x] ++ ac[:b]}
end
end
)
end
Examples
bifurcate([1, 2, 3, 4], fn x -> rem(x, 2) == 0 end)
# %{a: [4, 2], b: [3, 1]}
You can contribute to this project by sending a pull request with your new code snippets, or by creating a new issue if you want that a new section or snippet is added. Here you have the alphabetical list of contributors of this repository.
This project was developed by dreamingechoes. It adheres to its code of conduct and contributing guidelines, and uses an equivalent license.