Created
August 30, 2019 01:41
-
-
Save rsalgado/2e1ee527d040dd4e8657bf49590f6063 to your computer and use it in GitHub Desktop.
Small Elixir Wrapper of Erlang Arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ArrayWrapper do | |
@behaviour Access | |
defstruct erlang_array: :array.new() | |
@impl Access | |
def fetch(%ArrayWrapper{erlang_array: array}, key) | |
when is_integer(key) and (key >= 0) do | |
case :array.get(key, array) do | |
:undefined -> :error | |
value -> {:ok, value} | |
end | |
end | |
@impl Access | |
def get_and_update(%ArrayWrapper{erlang_array: array} = wrapper, key, func) | |
when is_integer(key) and (key >= 0) do | |
value = wrapper[key] # Fetch the value | |
case func.(value) do | |
{get_value, update_value} -> | |
wrapper = %{wrapper | erlang_array: :array.set(key, update_value, array)} | |
# Return the get value and the struct with the updated array | |
{get_value, wrapper} | |
:pop -> | |
wrapper = %{wrapper | erlang_array: :array.reset(key, array)} | |
# Return the value and the struct with the updated array (without entry) | |
{value, wrapper} | |
end | |
end | |
@impl Access | |
def pop(%ArrayWrapper{erlang_array: array} = wrapper, key) | |
when is_integer(key) and (key >= 0) do | |
value = wrapper[key] | |
wrapper = %{wrapper | erlang_array: :array.reset(key, array)} | |
# Return the value and the struct with the updated array (without entry) | |
{value, wrapper} | |
end | |
def to_list(%ArrayWrapper{erlang_array: array}) do | |
:array.to_list(array) | |
end | |
def size(%ArrayWrapper{erlang_array: array}) do | |
:array.size(array) | |
end | |
defimpl Inspect, for: ArrayWrapper do | |
import Inspect.Algebra | |
def inspect(array_wrapper, opts) do | |
concat(["#ArrayWrapper<", to_doc(ArrayWrapper.to_list(array_wrapper), opts), ">"]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment