Skip to content

Instantly share code, notes, and snippets.

@skrat
Created June 28, 2016 18:19
Show Gist options
  • Save skrat/16574c79568cb595c4aece1e35864b52 to your computer and use it in GitHub Desktop.
Save skrat/16574c79568cb595c4aece1e35864b52 to your computer and use it in GitHub Desktop.
(def lookup-sentinel #?(:clj ::not-found :cljs (js-obj))
(def pending-sentinel #?(:clj ::pending :cljs (js-obj))
(defn memoize-async
[f]
(let [>in (chan)
pending (pub >in :args)
mem (atom {})]
(letfn
[(memoized [& args]
(go
(let [v (get @mem args lookup-sentinel)]
(condp identical? v
lookup-sentinel
(do
(swap! mem assoc args pending-sentinel)
(go
(let [ret (<! (apply f args))]
(swap! mem assoc args ret)
(put! >in {:args args :ret ret})))
(<! (apply memoized args)))
pending-sentinel
(let [<out (chan 1)]
(sub pending args <out)
(:ret (<! <out)))
v))))]
memoized)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment