Skip to content

Commit 45f6d6c

Browse files
committed
Remove unneeded list concat on reduce
The original reduce implementation simply converted the buffer to a list and used the normal list reduce implementation. Conversion to a list involves a list concatenation which can be removed by manually iterating through the a and b lists.
1 parent 910843d commit 45f6d6c

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

lib/circular_buffer.ex

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,15 @@ defmodule CircularBuffer do
127127
end
128128

129129
def reduce(cb, acc, fun) do
130-
Enumerable.List.reduce(CB.to_list(cb), acc, fun)
130+
do_reduce(cb.b, Enum.reverse(cb.a), acc, fun)
131131
end
132132

133+
defp do_reduce(_b, _a, {:halt, acc}, _fun), do: {:halted, acc}
134+
defp do_reduce(b, a, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(b, a, &1, fun)}
135+
defp do_reduce([], [], {:cont, acc}, _fun), do: {:done, acc}
136+
defp do_reduce([], [h | t], {:cont, acc}, fun), do: do_reduce([], t, fun.(h, acc), fun)
137+
defp do_reduce([h | t], a, {:cont, acc}, fun), do: do_reduce(t, a, fun.(h, acc), fun)
138+
133139
def slice(_cb) do
134140
{:error, __MODULE__}
135141
end

0 commit comments

Comments
 (0)