Skip to content

Commit c7bf764

Browse files
albertoalmagrojosevalim
authored andcommitted
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
1 parent 88326e7 commit c7bf764

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
@@ -412,6 +412,9 @@ defmodule Enum do
412412
iex> Enum.chunk_every([1, 2, 3, 4], 10)
413413
[[1, 2, 3, 4]]
414414
415+
iex> Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, [])
416+
[[1, 2], [4, 5]]
417+
415418
"""
416419
@spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]
417420
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
@@ -25,7 +25,7 @@ defmodule Stream.Reducers do
2525
end
2626

2727
after_fun = fn {acc_buffer, acc_count} ->
28-
if leftover == :discard or acc_count == 0 do
28+
if leftover == :discard or acc_count == 0 or (step > count and count == acc_count) do
2929
{:cont, []}
3030
else
3131
{: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
@@ -71,6 +71,10 @@ defmodule EnumTest do
7171
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, []) == [[1, 2, 3], [3, 4, 5], [5, 6]]
7272
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 3, []) == [[1, 2, 3], [4, 5, 6]]
7373
assert Enum.chunk_every([1, 2, 3, 4, 5], 4, 4, 6..10) == [[1, 2, 3, 4], [5, 6, 7, 8]]
74+
assert Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, []) == [[1, 2], [4, 5]]
75+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6], 2, 3, []) == [[1, 2], [4, 5]]
76+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6, 7], 2, 3, []) == [[1, 2], [4, 5], [7]]
77+
assert Enum.chunk_every([1, 2, 3, 4, 5, 6, 7], 2, 3, [8]) == [[1, 2], [4, 5], [7, 8]]
7478
end
7579

7680
test "chunk_by/2" do

0 commit comments

Comments
 (0)