Skip to content

Commit 14bd16e

Browse files
bendlasDavid Nolen
authored and
David Nolen
committed
CLJS-417: Fix cljs.core/mod for negative numbers. Original operation available as cljs.core/js-mod.
1 parent ea18c02 commit 14bd16e

File tree

3 files changed

+11
-5
lines changed

3 files changed

+11
-5
lines changed

src/clj/cljs/core.clj

+1-1
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@
290290
([x y] (list 'js* "((~{} < ~{}) ? ~{} : ~{})" x y x y))
291291
([x y & more] `(min (min ~x ~y) ~@more)))
292292

293-
(defmacro mod [num div]
293+
(defmacro js-mod [num div]
294294
(list 'js* "(~{} % ~{})" num div))
295295

296296
(defmacro bit-not [x]

src/cljs/cljs/core.cljs

+9-4
Original file line numberDiff line numberDiff line change
@@ -1311,15 +1311,20 @@ reduces them without incurring seq initialization"
13111311
[x]
13121312
(fix x))
13131313

1314+
(defn js-mod
1315+
"Modulus of num and div with original javascript behavior. i.e. bug for negative numbers"
1316+
[n d]
1317+
(cljs.core/js-mod n d))
1318+
13141319
(defn mod
13151320
"Modulus of num and div. Truncates toward negative infinity."
13161321
[n d]
1317-
(cljs.core/mod n d))
1322+
(js-mod (+ (js-mod n d) d) d))
13181323

13191324
(defn quot
13201325
"quot[ient] of dividing numerator by denominator."
13211326
[n d]
1322-
(let [rem (mod n d)]
1327+
(let [rem (js-mod n d)]
13231328
(fix (/ (- n rem) d))))
13241329

13251330
(defn rem
@@ -1527,7 +1532,7 @@ reduces them without incurring seq initialization"
15271532
(loop [h 0 s (seq m)]
15281533
(if s
15291534
(let [e (first s)]
1530-
(recur (mod (+ h (bit-xor (hash (key e)) (hash (val e))))
1535+
(recur (js-mod (+ h (bit-xor (hash (key e)) (hash (val e))))
15311536
4503599627370496)
15321537
(next s)))
15331538
h)))
@@ -1537,7 +1542,7 @@ reduces them without incurring seq initialization"
15371542
(loop [h 0 s (seq s)]
15381543
(if s
15391544
(let [e (first s)]
1540-
(recur (mod (+ h (hash e)) 4503599627370496)
1545+
(recur (js-mod (+ h (hash e)) 4503599627370496)
15411546
(next s)))
15421547
h)))
15431548

test/cljs/cljs/core_test.cljs

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
(assert (= (apply mod [4 2]) 0))
157157
(assert (= (mod 3 2) 1))
158158
(assert (= (apply mod [3 2]) 1))
159+
(assert (= (mod -2 5) 3))
159160

160161
(assert (= [4 3 2 1 0] (loop [i 0 j ()]
161162
(if (< i 5)

0 commit comments

Comments
 (0)