Skip to content

Instantly share code, notes, and snippets.

@brentonashworth
Created February 9, 2012 13:00
Show Gist options
  • Save brentonashworth/1779843 to your computer and use it in GitHub Desktop.
Save brentonashworth/1779843 to your computer and use it in GitHub Desktop.
(ns hack.queue)
(defn log [form]
(.log js/console (pr-str form)))
(defprotocol Queue
(pop [this])
(empty? [this])
(peek [this])
(append [this x]))
(defn make-queue []
(let [q (atom [])]
(reify Queue
(pop [this]
(let [x (first @q)]
(swap! q (fn [v] (vec (next v))))
x))
(peek [this]
(first @q))
(empty? [this]
(not (boolean (seq @q))))
(append [this x]
(swap! q conj x)))))
(comment
(def queue (make-queue))
(append queue "Hello")
(peek queue)
(empty? queue)
(pop queue)
(empty? queue)
)
;; Loop
(defprotocol Loop
(start [this])
(continue [this])
(stop [this]))
(defn make-loop [poll process queue]
(let [state (atom {:running false
:timeout nil})]
(reify Loop
(start [this]
(swap! state assoc-in [:running] true)
(continue this))
(continue [this]
(when (:running @state)
(when (:timeout @state)
(.clearTimeout js/window (:timeout @state))
(swap! state assoc-in [:timeout] nil))
(poll queue)
(if-not (empty? queue)
(do (process (pop queue))
(swap! state assoc-in [:timeout] (.setTimeout js/window (fn [] (continue this)) 10)))
(swap! state assoc-in [:timeout] (.setTimeout js/window (fn [] (continue this)) 1000)))))
(stop [this]
(swap! state assoc-in [:running] false)))))
(defn process-next-message [msg]
(log "processing next message...")
(log msg))
(defn poll [queue]
(log "Polling...")
(log queue))
(comment
(def loop (make-loop poll process-next-message queue))
(start loop)
(append queue "Hello")
(stop loop)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment