Skip to content

Commit eb7e098

Browse files
albertoalmagroJosé Valim
authored and
José Valim
committed
Fix Stream.chunk_every/4 odd results when step > count (#7114)
Stream.chunk_every/4 was giving odd results when step was greater than count and the last element of the enumerable was the same as last chunk's last element. This commit fixes this issue and adds tests for different scenarios when step > count. It also adds a doctest example to reflect this in the documentation and test it simultaneously. Fixes #7096 Signed-off-by: José Valim <[email protected]>
1 parent 57a52b9 commit eb7e098

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

lib/elixir/lib/enum.ex

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,9 @@ defmodule Enum do
362362
iex> Enum.chunk_every([1, 2, 3, 4], 10)
363363
[[1, 2, 3, 4]]
364364
365+
iex> Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, [])
366+
[[1, 2], [4, 5]]
367+
365368
"""
366369
@spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]
367370
def chunk_every(enumerable, count, step, leftover \\ [])

lib/elixir/lib/stream/reducers.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ defmodule Stream.Reducers do
2222
{:cont, new_state}
2323
end
2424
end, fn {acc_buffer, acc_count} ->
25-
if leftover == :discard or acc_count == 0 do
25+
if leftover == :discard or acc_count == 0 or (step > count and count == acc_count) do
2626
{:cont, []}
2727
else
2828
{:cont, :lists.reverse(acc_buffer, Enum.take(leftover, count - acc_count)), []}

lib/elixir/test/elixir/enum_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ defmodule EnumTest do
7070
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, []) == [[1, 2, 3], [3, 4, 5], [5, 6]]
7171
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 3, []) == [[1, 2, 3], [4, 5, 6]]
7272
assert Enum.chunk_every([1, 2, 3, 4, 5], 4, 4, 6..10) == [[1, 2, 3, 4], [5, 6, 7, 8]]
73+
assert Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, []) == [[1, 2], [4, 5]]
74+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 2, 3, []) == [[1, 2], [4, 5]]
75+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6, 7], 2, 3, []) == [[1, 2], [4, 5], [7]]
76+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6, 7], 2, 3, [8]) == [[1, 2], [4, 5], [7, 8]]
7377
end
7478

7579
test "chunk_by/2" do

0 commit comments

Comments
 (0)