Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CoffeeScript use %% for modulo instead of the standard javascript operator %

In the CoffeeScript documentation on operators it says that you can use %% for true mathematical modulo, but there is no explanation as to why this is different from the "modulo operator" % in JavaScript.

Further down it says that a %% b in CoffeeScript is equivalent to writing (a % b + b) % b in JavaScript but this seem to produce the same results for most simple cases.

like image 920
Mathias Avatar asked Apr 17 '14 06:04

Mathias


People also ask

Is CoffeeScript the same as JavaScript?

Bottom Line. One crucial difference between the two languages is that TypeScript is the superset of JavaScript while CoffeeScript is a language which is an enhanced version of JavaScript. Not just these two languages but there are other languages such as Dart, Kotlin, etc. which can be compiled into JavaScript.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.


2 Answers

I did find the answer in another StackOverflow question and answer JavaScript % (modulo) gives a negative result for negative numbers and I wanted to share it for people who like me only looked for a "CoffeeScript" related explanations and thus have a hard time finding the correct answer.

The reason for using a %% b which compiles to (a % b + b) % b is that for negative number, like -5 % 3, JavaScript will produce a negative number -5 % 3 = -2 while the correct mathematical answer should be -5 % 3 = 1.

The accepted answer refers to an article on the JavaScript modulo bug which explains it well.

like image 155
Mathias Avatar answered Oct 27 '22 13:10

Mathias


Made no sense for me at first, so I believe it needs an example

check = (a,b) ->
  c = (b*Math.floor(a/b)) + a%b
  d = (b*Math.floor(a/b)) + a%%b
  console.log(
    [c, c == a]
    [d, d == a]
  )

check  78, 33 # [ 78, true ] [ 78, true ]
check -78, 33 # [ -111, false ] [ -78, true ]

###
 78 mod 33 = 12
-78 mod 33 = 21

check:  78 = 33 *  2 + 12
check: -78 = 33 * -3 + 21
###

Looks like modulo is a mathematical trick to be able to use one formula for all numbers instead of one for negatives and second for positives. Don't know if it's more than just a trick and have some intrinsic meaning though.

like image 34
user619271 Avatar answered Oct 27 '22 13:10

user619271