aboutsummaryrefslogtreecommitdiff
path: root/lib/util/stream.ex
blob: b143bc1aca88940d21e28f2b7c8e626597033845 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defmodule Thulani.Util.Stream do
  def take_until(enum, fun) when :erlang.is_function(fun, 1) do
    lazy(enum, fn f1 ->
      fn entry, acc ->
        if(fun.(entry)) do
          {:cont, result} = f1.(entry, acc)
          {:halt, result}
        else
          f1.(entry, acc)
        end
      end
    end)
  end

  @compile {:inline, lazy: 2}

  defp lazy(%Stream{done: nil, funs: funs} = lazy, fun), do: %{lazy | funs: [fun | funs]}
  defp lazy(enum, fun), do: %Stream{enum: enum, funs: [fun]}
end