Skip to content

Commit e5fcef3

Browse files
TroushJosé Valim
authored and
José Valim
committed
Make sure to return nil if enumerable halts
Fix issue #5004 Signed-off-by: José Valim <[email protected]>
1 parent 9081a7a commit e5fcef3

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

lib/elixir/lib/enum.ex

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -861,13 +861,13 @@ defmodule Enum do
861861

862862
def find_index(enumerable, fun) do
863863
res =
864-
Enumerable.reduce(enumerable, {:cont, 0}, fn(entry, acc) ->
865-
if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}
864+
Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn(entry, {status, index}) ->
865+
if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}}
866866
end)
867867

868868
case res do
869-
{:halted, entry} -> entry
870-
{:done, _} -> nil
869+
{_, {:found, index}} -> index
870+
{_, {:not_found, _}} -> nil
871871
end
872872
end
873873

lib/elixir/test/elixir/enum_test.exs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ defmodule EnumTest do
195195
test "find_index/2" do
196196
assert Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) == nil
197197
assert Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) == 1
198+
assert Stream.take(1..3, 3) |> Enum.find_index(fn _ -> false end) == nil
199+
assert Stream.take(1..6, 6) |> Enum.find_index(fn x -> x == 5 end) == 4
198200
end
199201

200202
test "find_value/2" do

0 commit comments

Comments
 (0)