Skip to content

Commit

Permalink
CLJ-719: call correct diff function for arrays as first argument
Browse files Browse the repository at this point in the history
Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information
Stuart Halloway authored and stuarthalloway committed Jan 28, 2011
1 parent 553f487 commit 76c1a58
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
38 changes: 21 additions & 17 deletions src/clj/clojure/data.clj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
clojure.data
(:require [clojure.set :as set]))

(declare diff)

(defn- atom-diff
"Internal helper for diff."
[a b]
Expand All @@ -28,7 +30,23 @@
(vec (repeat (apply max (keys m)) nil))
m)))

(declare diff)
(defn- diff-associative
"Diff associative things a and b, comparing only keys in ks."
[a b ks]
(reduce
(fn [diff1 diff2]
(map merge diff1 diff2))
[nil nil nil]
(map
(fn [k] (map #(when % {k %}) (diff (get a k) (get b k))))
ks)))

(defn- diff-sequential
[a b]
(vec (map vectorize (diff-associative
(if (vector? a) a (vec a))
(if (vector? b) b (vec b))
(range (max (count a) (count b)))))))

(defprotocol ^{:added "1.3"} EqualityPartition
"Implementation detail. Subject to change."
Expand All @@ -44,21 +62,10 @@

(extend Object
Diff
{:diff-similar atom-diff}
{:diff-similar (fn [a b] ((if (.. a getClass isArray) diff-sequential atom-diff) a b))}
EqualityPartition
{:equality-partition (fn [x] (if (.. x getClass isArray) :sequential :atom))})

(defn- diff-associative
"Diff associative things a and b, comparing only keys in ks."
[a b ks]
(reduce
(fn [diff1 diff2]
(map merge diff1 diff2))
[nil nil nil]
(map
(fn [k] (map #(when % {k %}) (diff (get a k) (get b k))))
ks)))

(extend-protocol EqualityPartition
nil
(equality-partition [x] :atom)
Expand Down Expand Up @@ -88,10 +95,7 @@

java.util.List
(diff-similar [a b]
(vec (map vectorize (diff-associative
(if (vector? a) a (vec a))
(if (vector? b) b (vec b))
(range (max (count a) (count b)))))))
(diff-sequential a b))

java.util.Map
(diff-similar [a b]
Expand Down
4 changes: 3 additions & 1 deletion test/clojure/test_clojure/data.clj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
[#{:a} #{:b} #{:c :d}] #{:a :c :d} #{:b :c :d}
[nil nil {:a 1}] {:a 1} {:a 1}
[{:a #{2}} {:a #{4}} {:a #{3}}] {:a #{2 3}} {:a #{3 4}}
[#{1} #{3} #{2}] (HashSet. [1 2]) (HashSet. [2 3])
[#{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]}}))

0 comments on commit 76c1a58

Please sign in to comment.