Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Last active September 27, 2020 10:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheharyarn/9628dadbbf424d1f91e5734130b5a588 to your computer and use it in GitHub Desktop.
Save sheharyarn/9628dadbbf424d1f91e5734130b5a588 to your computer and use it in GitHub Desktop.
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