Skip to content

Instantly share code, notes, and snippets.

@sander
Created November 30, 2015 19:21
Show Gist options
  • Save sander/30c3c36c005b3eee71fc to your computer and use it in GitHub Desktop.
Save sander/30c3c36c005b3eee71fc to your computer and use it in GitHub Desktop.
(defn- before [begin]
(fn [{:keys [time]}]
(<= time begin)))
(defn- weighted [weigh now ival]
(fn [{:keys [time] :as entry}]
(assoc entry :weight (weigh (- 1 (/ (- now time) ival))))))
(defn- pop-while [pred queue]
(loop [q queue]
(if (and (not (empty? q))
(pred (peek q)))
(recur (pop q))
q)))
(defn sliding-window [ival weigh]
(fn [xf]
(let [content (atom #queue [])]
(fn
([] (xf))
([result] (xf result))
([result {:keys [time val] :as entry}]
(let [c (swap! content #(pop-while (before (- time ival))
(if val (conj % entry) %)))]
(xf result (map (weighted weigh time ival) c))))))))
(defn sum-weights [v]
(apply + (map :weight v)))
(defn sliding-window-weight [ival weigh]
(comp (sliding-window ival weigh)
(map sum-weights)
(map #(/ % ival))))
(defn weights->rate [long-term short-term]
(+ 80 (* 20 (- short-term long-term))))
(def fake-data
[{:time 1 :val :foo}
{:time 3 :val :bar}
{:time 6}
{:time 7 :val :baz}
{:time 7.1 :val :qux}
{:time 7.2 :val :asdf}
{:time 7.3 :val :qwerty}
{:time 7.4 :val :mnbv}
{:time 8}
{:time 9}
{:time 10}
{:time 11}
{:time 12}])
(pprint
(map weights->rate
(into [] (sliding-window-weight 6 identity) fake-data)
(into [] (sliding-window-weight 2 identity) fake-data)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment