Skip to content

Instantly share code, notes, and snippets.

@tallakt
Created August 26, 2015 08:38
Show Gist options
  • Save tallakt/d689acb06b794d59a588 to your computer and use it in GitHub Desktop.
Save tallakt/d689acb06b794d59a588 to your computer and use it in GitHub Desktop.
defmodule Between do
@doc """
## Examples
iex> list = for x <- 1000..1031, rem(x, 5) != 0, do: x
iex> chunks = Between.chunk_between(list, fn a, b -> b - a != 1 end)
iex> IO.inspect
[[1001, 1002, 1003, 1004], [1006, 1007, 1008, 1009], [1011, 1012, 1013, 1014],
[1016, 1017, 1018, 1019], [1021, 1022, 1023, 1024], [1026, 1027, 1028, 1029],
[1031]]
"""
def chunk_between(enum, f) do
chunks = %{result: [], current: Enum.take(enum, 1)}
chunks =
enum
|> Enum.chunk(2, 1)
|> Enum.reduce(chunks, fn [a, b], acc ->
if f.(a,b) do
%{acc | result: [acc.current | acc.result], current: [b]}
else
%{acc | current: [b | acc.current]}
end
end)
result =
if Enum.empty?(chunks.current) do
chunks.result
else
[chunks.current | chunks.result]
end
result
|> Enum.reverse
|> Enum.map(&Enum.reverse/1)
end
end
ExUnit.start()
defmodule Between.Test do
use ExUnit.Case
doctest Between, import: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment