Created
November 21, 2021 15:05
-
-
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
This file contains 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
(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