From a74f4a023a8c51b5830bc6e4eeda8a86c70f5b14 Mon Sep 17 00:00:00 2001 From: Kurtis Rainbolt-Greene Date: Wed, 22 Feb 2023 13:48:07 -0800 Subject: [PATCH] Adding a very common operation so users don't have to --- lib/stash.ex | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/stash.ex b/lib/stash.ex index eedf7cc..3816eb2 100644 --- a/lib/stash.ex +++ b/lib/stash.ex @@ -63,6 +63,15 @@ defmodule Stash do :ets.insert(cache, { key, value }) end + @spec getsert(atom, any, () -> any | any) :: any + deft getsert(cache, key, function) when is_function(function, 0) do + get(cache, key) || set(cache, key, function.()) + end + + deft getsert(cache, key, value) do + get(cache, key) || set(cache, key, value) + end + @doc """ Increments a key directly in the cache by `count`. If the key does not exist it is set to `initial` before **then** being incremented.