Skip to content

Instantly share code, notes, and snippets.

@UA3MQJ
Forked from brweber2/Benum.ex
Created February 13, 2019 10:02
Show Gist options
  • Save UA3MQJ/47cf6c03bc586c7a9465ad614a18efb7 to your computer and use it in GitHub Desktop.
Save UA3MQJ/47cf6c03bc586c7a9465ad614a18efb7 to your computer and use it in GitHub Desktop.
Elixir Enumerable for binaries....
defmodule Benum do
defimpl Enumerable, for: BitString do
def count(collection) when is_binary(collection) do
{:ok, Enum.reduce(collection, 0, fn v, acc -> acc + 1 end)}
end
def count(collection) do
{:error, __MODULE__}
end
def member?(collection, value) when is_binary(collection) do
{:ok, Enum.any?(collection, fn v -> value == v end)}
end
def member?(collection, value) do
{:error, __MODULE__}
end
def reduce(b, {:halt, acc}, _fun) when is_binary(b) do
{:halted, acc}
end
def reduce(b, {:suspend, acc}, fun) when is_binary(b) do
{:suspended, acc, &reduce(b, &1, fun)}
end
def reduce(<<>>, {:cont, acc}, _fun) do
{:done, acc}
end
def reduce(<<h :: bytes-size(1), t :: binary>>, {:cont, acc}, fun) do
reduce(t, fun.(h, acc), fun)
end
end
end
# USAGE EXAMPLES
# NOTE: IN ORDER TO GET THIS TO WORK I HAD TO USE MIX_ENV=prod (for protocol consolidation)
# the easier way to do this is to add the following line to your project definition in mix.exs:
# consolidate_protocols: true,
$ MIX_ENV=prod iex -S mix
iex>> import Benum
iex>> Enum.count "foobar"
6
iex>> Enum.count <<1,2,3>>
3
iex>> Enum.count ""
0
iex>> Enum.member? "foobar", "b"
true
iex>> Enum.member? "foobar", <<98>>
true
iex>> Enum.member? "foobar", "x"
false
iex>> Enum.map("foobar", &String.upcase/1) |> Enum.into <<>>
"FOOBAR"
iex>> Enum.join "foobar", "."
"f.o.o.b.a.r"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment