krzysztof-w
7/28/2016 - 10:34 PM

test.ex

@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