Last active
September 27, 2020 10:05
-
-
Save sheharyarn/9628dadbbf424d1f91e5734130b5a588 to your computer and use it in GitHub Desktop.
Simple Memoization in Elixir (using FastGlobal)
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 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