Skip to content

Instantly share code, notes, and snippets.

@pleasetrythisathome
Last active September 3, 2015 18:17
Show Gist options
  • Save pleasetrythisathome/7abfe4d3c1cbbf5bfe39 to your computer and use it in GitHub Desktop.
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
(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