Created
June 28, 2016 18:19
-
-
Save skrat/16574c79568cb595c4aece1e35864b52 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(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