ClojureScript

cljs.core/mod incorrect for negative numbers

Details

  • Type: Defect Defect
  • Status: Closed Closed
  • Priority: Major Major
  • Resolution: Completed
  • Affects Version/s: None
  • Fix Version/s: None
  • Component/s: None
  • Labels:
    None

Description

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

-2 % 5 => -2

which carries over to cljs.core/mod

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

suggests defining modulo as:

Number.prototype.mod = function(n) {
  return ((this%n)+n)%n;
}

ClojureScript's mod should use this workaround

Activity

Hide
Herwig Hochleitner added a comment -

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.

Show
Herwig Hochleitner added a comment - 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.
Hide
Richard Hull added a comment -

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 ?

Show
Richard Hull added a comment - 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 ?
Hide
David Nolen added a comment -

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

Show
David Nolen added a comment - Arithmetic functions only operate on numbers, the behavior is undefined for any other input types.

People

Vote (0)
Watch (2)

Dates

  • Created:
    Updated:
    Resolved: