Skip to content

Instantly share code, notes, and snippets.

@DarrenN
Last active December 31, 2015 08:49
Show Gist options
  • Save DarrenN/7963230 to your computer and use it in GitHub Desktop.
Save DarrenN/7963230 to your computer and use it in GitHub Desktop.
Buffered vector as a value - not stored in an atom
(ns DarrenN.stateless.buffer)
;; create-buffer returns a vector scoped to size. When new items are added
;; they are passed to functions in add-listeners. If the vector is at its
;; size limit then items are shifted off the front of the vector and
;; passed to the functions in destroy-listeners
;; Callbacks for adding/removing item from vector
(def destroy-listeners [(fn [i] (print (str i " removed")))])
(def add-listeners [(fn [i] (print (str i " added")))])
(defn add-item [i v]
"Add an item to the vector and call listeners on added item"
(doseq [f add-listeners] (f i))
(conj v i))
(defn remove-item [v]
"Remove item from vector triggering listeners on removed item"
(doseq [f destroy-listeners] (f (first v)))
(vec (rest v)))
(defn create-buffer [size v]
"Return a function that keeps a vector at size when adding"
(fn [item v]
(let [newv (add-item item v)]
(if (> (count v) size)
(remove-item newv)
newv))))
;; Loop from 0 to 99 filling a 10 slot queue
(let [ct 0
queue (create-buffer 10 [])
vt []]
(loop [v vt
c ct]
(when (> 100 c)
(recur (queue c v) (inc c)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment