Skip to content

Instantly share code, notes, and snippets.

@ragnard
Last active April 20, 2017 14:41
Show Gist options
  • Save ragnard/6108177 to your computer and use it in GitHub Desktop.
Save ragnard/6108177 to your computer and use it in GitHub Desktop.
Exploring core.async, core.match and David Nolens async-tests repository.
(defn debounce
([source msecs edge]
(debounce (chan) source msecs edge))
([sink source msecs edge]
(go (loop [state ::init last nil chans [source]]
(let [[_ timer] chans
[v c] (alts! chans)]
(match [state c edge]
[::init source :leading] (do (>! sink v)
(recur ::debouncing nil (conj chans (timeout msecs))))
[::init source :falling] (recur ::debouncing v (conj chans (timeout msecs)))
[::debouncing source _ ] (recur ::debouncing v (conj (pop chans) (timeout msecs)))
[_ timer :falling] (do (>! sink last)
(recur ::init nil (pop chans)))
[_ timer :leading] (recur ::init nil (pop chans))))))
sink))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment