Created
February 7, 2018 09:08
-
-
Save andersenleo/c169b4a5dda59be12e7005f657bd6849 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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