cljs.core/mod incorrect for negative numbers

Description

JavaScript's % (modulo) operator gives incorrect answers for negative numbers, e.g.

which carries over to cljs.core/mod

This blog: http://javascript.about.com/od/problemsolving/a/modulobug.htm

suggests defining modulo as:

ClojureScript's mod should use this workaround

Environment

None

Attachments

1

Activity

Show:

David Nolen June 4, 2013 at 10:05 PM

Arithmetic functions only operate on numbers, the behavior is undefined for any other input types.

Richard Hull June 4, 2013 at 9:22 PM

Found a corner case where this implementation of mod fails - if the modulus is a stringified number then it doesn't work. Clearly a string ought not be passed in the first place, but there is no indication other than a wrong result.

compare (rem 10 "4") and (mod 10 "4") and (mod 10 4)
then try (rem 10 "3") and (mod 10 "3") and (mod 10 3)

Some worked examples here: https://gist.github.com/rm-hull/5708459

Should js/parseInt be used in the body of the mod function to coerce to a number ?

Herwig Hochleitner November 12, 2012 at 10:41 AM

Attached patch renames cljs.core/mod to cljs.core/js-mod, along with occurrences in cljs.core.

cljs.core/mod is redefined with fix for negative numbers.

Completed

Details

Assignee

Reporter

Priority

Created November 12, 2012 at 10:08 AM
Updated July 27, 2013 at 9:56 PM
Resolved July 27, 2013 at 9:56 PM