Skip to content

Instantly share code, notes, and snippets.

@danownsthisspace
Created November 21, 2021 15:05
Show Gist options
  • Save danownsthisspace/f10f85ab51681139255a920f9885c74c to your computer and use it in GitHub Desktop.
Save danownsthisspace/f10f85ab51681139255a920f9885c74c to your computer and use it in GitHub Desktop.
A function wrapper that ensures that a function can only be called once
(ns scratch.core)
(defn say-hi [username]
(let [s (str "hello, " username)]
(Thread/sleep (rand 100))
(println s)
s))
(comment (say-hi "Steve"))
(defn wrap-once
"Returns a fn that wraps given function `f` so that:
- First call returns {:okay (apply f args)}.
- Subsequent calls return nil, without executing `f`."
[f]
(let [run?_ (atom false)]
(fn once-fn [& args]
(when (compare-and-set! run?_ false true)
{:okay (apply f args)}))))
(comment
(let [wf (wrap-once say-hi)]
(println "---")
[(future (wf "Steve 1"))
(future (wf "Steve 2"))
(future (wf "Steve 3"))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment