Skip to content

Instantly share code, notes, and snippets.

@andersenleo
Created February 7, 2018 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersenleo/c169b4a5dda59be12e7005f657bd6849 to your computer and use it in GitHub Desktop.
Save andersenleo/c169b4a5dda59be12e7005f657bd6849 to your computer and use it in GitHub Desktop.
(def entries [{:id 1 :value 88}
{:id 2 :value 99}
{:id 1 :value 98}
{:id 3 :value 5}
{:id 2 :value 100}
{:id 3 :value 10}
{:id 1 :value 150}])
(defn make-running-diff-map []
(let [state (atom {})]
;; Map function
(fn [{:as entry :keys [id value]}]
(get (swap! state (fn [s]
(update s id (fn [{:as p
pvalue :value}]
(if p
;; Add a :diff
(assoc entry :diff (- value pvalue))
;; no previous entry
entry)
))))
id))))
(map (make-running-diff-map) entries)
;; => ({:id 1, :value 88} {:id 2, :value 99} {:id 1, :value 98, :diff 10} {:id 3, :value 5} {:id 2, :value 100, :diff 1} {:id 3, :value 10, :diff 5} {:id 1, :value 150, :diff 52})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment