Skip to content

Instantly share code, notes, and snippets.

@wende
Last active July 28, 2016 22:35
Show Gist options
  • Save wende/ac6cf78217b957c1324ca29c5bc0de28 to your computer and use it in GitHub Desktop.
Save wende/ac6cf78217b957c1324ca29c5bc0de28 to your computer and use it in GitHub Desktop.
@spec chunk(t, pos_integer, pos_integer, t | nil) :: [list]
def chunk(enumerable, count, step, leftover \\ nil)
when is_integer(count) and count > 0 and is_integer(step) and step > 0 do
limit = :erlang.max(count, step)
{acc, {buffer, i}} =
reduce(enumerable, {[], {[], 0}}, R.chunk(count, step, limit))
if is_nil(leftover) || i == 0 do
:lists.reverse(acc)
else
buffer = :lists.reverse(buffer, take(leftover, count - i))
:lists.reverse([buffer | acc])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment