Last active
September 3, 2015 18:17
-
-
Save pleasetrythisathome/7abfe4d3c1cbbf5bfe39 to your computer and use it in GitHub Desktop.
debounce an action on a channel for values that produce the same result of a key-fn
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
(defn debounce | |
"debounce an action on a channel for values that produce the same result of a key-fn" | |
([f input-ch wait] (debounce f input-ch wait identity)) | |
([f input-ch wait key-fn] | |
;; keep a map of keys that have been triggered | |
(go-loop [debounced {}] | |
(let [[v c] (alts! (conj (vals debounced) input-ch))] | |
(if (= c input-ch) | |
(let [key (key-fn v)] | |
(if (get (into #{} (keys debounced)) key) ;; if our key is debounced | |
(recur debounced) ;; don't do anything | |
(recur (assoc debounced ;; add key to rebounced | |
key (go ;; go immediately returns a channel | |
(<! (timeout wait));; after wait returning key puts key onto the cannel | |
key))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment