Skip to content

Instantly share code, notes, and snippets.

@bfolkens
Created March 15, 2022 05:39
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 bfolkens/f2130521a97c7a994b5c7f66190a0c55 to your computer and use it in GitHub Desktop.
Save bfolkens/f2130521a97c7a994b5c7f66190a0c55 to your computer and use it in GitHub Desktop.
Collate a list of lists in sequence until the longest list is exhausted.
defmodule Util.Enum do
@doc ~S"""
Collates a list of lists in sequence until the longest
list is exhausted.
## Examples
iex> Util.Enum.collate([[1, 2, 3], [1, 2], [1, 2, 3, 4]])
[1, 1, 1, 2, 2, 2, 3, 3, 4]
iex> Util.Enum.collate([[], [1, 2], [1, 2, 3, 4]])
[1, 1, 2, 2, 3, 4]
iex> Util.Enum.collate([[1]])
[1]
iex> Util.Enum.collate([[]])
[]
iex> Util.Enum.collate([])
[]
"""
def collate(lists) do
lists
|> collate([])
|> Enum.reverse()
end
defp collate(lists, heads) when lists == [], do: heads
defp collate(lists, heads) do
{heads, tails} =
Enum.reduce(lists, {heads, []}, fn
[head | tail], {heads, tails} ->
{[head | heads], [tail | tails]}
[], {heads, tails} ->
{heads, tails}
end)
collate(tails, heads)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment