lib/memoize.ex

defmodule Memoize do
  @moduledoc """
  Simple `FastGlobal` based memoization module to cache function results.
  """

  @doc """
  Resolves the given key using the given resolver function.

  If the key is not found in the cache, the resolver function is called
  and the result is stored in the cache.
  If the key is found in the cache, the cached value is returned.

  ## Examples

      defmodule MyModule do
        def my_function(arg1, arg2) do
          Memoize.resolve({__MODULE__, :my_function, [arg1, arg2]}, fn ->
            # Do some expensive computation here
          end)
        end
      end
  """

  @spec resolve(key :: any, resolver :: function) :: any
  def resolve(key, resolver) when is_function(resolver, 0) do
    case get(key) do
      nil ->
        value = resolver.()
        put(key, value)
        value

      value ->
        value
    end
  end

  defdelegate get(key), to: FastGlobal, as: :get
  defdelegate put(key, value), to: FastGlobal, as: :put
end