Skip to content

Commit

Permalink
clojure.data/diff: cope with falsey values in maps
Browse files Browse the repository at this point in the history
Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information
philipa authored and stuarthalloway committed Aug 15, 2012
1 parent a4c2296 commit 9baebd0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/clj/clojure/data.clj
Expand Up @@ -30,6 +30,22 @@
(vec (repeat (apply max (keys m)) nil))
m)))

(defn- diff-associative-key
"Diff associative things a and b, comparing only the key k."
[a b k]
(let [va (get a k)
vb (get b k)
[a* b* ab] (diff va vb)
in-a (contains? a k)
in-b (contains? b k)
same (and in-a in-b
(or (not (nil? ab))
(and (nil? va) (nil? vb))))]
[(when (and in-a (or (not (nil? a*)) (not same))) {k a*})
(when (and in-b (or (not (nil? b*)) (not same))) {k b*})
(when same {k ab})
]))

(defn- diff-associative
"Diff associative things a and b, comparing only keys in ks."
[a b ks]
Expand All @@ -38,7 +54,7 @@
(doall (map merge diff1 diff2)))
[nil nil nil]
(map
(fn [k] (map #(when % {k %}) (diff (get a k) (get b k))))
(partial diff-associative-key a b)
ks)))

(defn- diff-sequential
Expand Down
3 changes: 2 additions & 1 deletion test/clojure/test_clojure/data.clj
Expand Up @@ -27,5 +27,6 @@
[#{1} #{3} #{2}] (HashSet. [1 2]) (HashSet. [2 3])
[nil nil [1 2]] [1 2] (into-array [1 2])
[nil nil [1 2]] (into-array [1 2]) [1 2]
[{:a {:c [1]}} {:a {:c [0]}} {:a {:c [nil 2] :b 1}}] {:a {:b 1 :c [1 2]}} {:a {:b 1 :c [0 2]}}))
[{:a {:c [1]}} {:a {:c [0]}} {:a {:c [nil 2] :b 1}}] {:a {:b 1 :c [1 2]}} {:a {:b 1 :c [0 2]}}
[{:a nil} {:a false} {:b nil :c false}] {:a nil :b nil :c false} {:a false :b nil :c false}))

0 comments on commit 9baebd0

Please sign in to comment.