Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Memoization in Elixir (using FastGlobal)
defmodule Memoize do
@moduledoc """
Simple memoization helper built on top of FastGlobal.
Remember to add `{:fastglobal, "~> 1.0"}` to your
dependencies first.
## Usage
def my_method do
Memoize.run :my_method, fn ->
# return something
end
end
## Other
Author: Sheharyar Naseer
License: MIT
Website: https://sheharyar.me
Find updates to this module at https://git.io/fNcBb
"""
# Public API
# ----------
@doc """
If previously saved value exists, return that else
perform memoization for given key and function.
"""
def run(key, fun) when is_atom(key) do
case get!(key) do
nil ->
value = fun.()
put!(key, value)
value
result ->
result
end
end
@doc "Force get value"
defdelegate get!(key), to: FastGlobal, as: :get
@doc "Force put value"
defdelegate put!(key, value), to: FastGlobal, as: :put
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment