Skip to content

Commit b803b3d

Browse files
author
dnolen
committed
CLJS-1200: compare behaves differently from Clojure
drop type check from cljs.core/compare and move into IComparable implementations. fast path in cljs.core/compare for numbers
1 parent dfad0d2 commit b803b3d

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

src/main/cljs/cljs/core.cljs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1103,7 +1103,9 @@
11031103

11041104
IComparable
11051105
(-compare [this other]
1106-
(garray/defaultCompare (.valueOf this) (.valueOf other))))
1106+
(if (instance? js/Date other)
1107+
(garray/defaultCompare (.valueOf this) (.valueOf other))
1108+
(throw (js/Error. (str "Cannot compare " this " to " other))))))
11071109

11081110
(extend-type number
11091111
IEquiv
@@ -1935,13 +1937,18 @@ reduces them without incurring seq initialization"
19351937

19361938
(nil? y) 1
19371939

1938-
(identical? (type x) (type y))
1939-
(if (implements? IComparable x)
1940-
(-compare ^not-native x y)
1941-
(garray/defaultCompare x y))
1940+
(number? x) (if (number? y)
1941+
(garray/defaultCompare x y)
1942+
(throw (js/Error. (str "Cannot compare " x " to " y))))
1943+
1944+
(satisfies? IComparable x)
1945+
(-compare x y)
19421946

19431947
:else
1944-
(throw (js/Error. "compare on non-nil objects of different types"))))
1948+
(if (and (or (string? x) (array? x) (true? x) (false? x))
1949+
(identical? (type x) (type y)))
1950+
(garray/defaultCompare x y)
1951+
(throw (js/Error. (str "Cannot compare " x " to " y))))))
19451952

19461953
(defn ^:private compare-indexed
19471954
"Compare indexed collection."
@@ -8783,16 +8790,28 @@ reduces them without incurring seq initialization"
87838790
;; IComparable
87848791
(extend-protocol IComparable
87858792
Symbol
8786-
(-compare [x y] (compare-symbols x y))
8793+
(-compare [x y]
8794+
(if (symbol? y)
8795+
(compare-symbols x y)
8796+
(throw (js/Error. (str "Cannot compare " x " to " y)))))
87878797

87888798
Keyword
8789-
(-compare [x y] (compare-keywords x y))
8799+
(-compare [x y]
8800+
(if (keyword? y)
8801+
(compare-keywords x y)
8802+
(throw (js/Error. (str "Cannot compare " x " to " y)))))
87908803

87918804
Subvec
8792-
(-compare [x y] (compare-indexed x y))
8805+
(-compare [x y]
8806+
(if (vector? y)
8807+
(compare-indexed x y)
8808+
(throw (js/Error. (str "Cannot compare " x " to " y)))))
87938809

87948810
PersistentVector
8795-
(-compare [x y] (compare-indexed x y)))
8811+
(-compare [x y]
8812+
(if (vector? y)
8813+
(compare-indexed x y)
8814+
(throw (js/Error. (str "Cannot compare " x " to " y))))))
87968815

87978816
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Reference Types ;;;;;;;;;;;;;;;;
87988817

0 commit comments

Comments
 (0)