Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate modulo of negative integers in JavaScript?

I'm trying to iterate over an array of jQuery objects, by incrementing or decrementing by 1. So, for the decrementing part, I use this code:

var splitted_id = currentDiv.attr('id').split('_');
var indexOfDivToGo = parseInt(splitted_id[1]);
indexOfDivToGo = (indexOfDivToGo-1) % allDivs.length;
var divToGo = allDivs[indexOfDivToGo];

so I have 4 elements with id's:

div_0
div_1
div_2
div_3

I was expecting it to iterate as 3 - 2 - 1 - 0 - 3 - 2 - etc..

but it returns -1 after the zero, therefore it's stuck. So it iterates as:

3 - 2 - 1 - 0 - -1 - stuck

I know I can probably fix it by changing the second line of my code to

indexOfDivToGo = (indexOfDivToGo-1 + allDivs.length) % allDivs.length;

but I wonder why JavaScript is not calculating negative mods. Maybe this will help another coder fellow too.

like image 663
jeff Avatar asked Sep 04 '13 15:09

jeff


Video Answer


2 Answers

You can try this :p-

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

Check out this

like image 78
Rahul Tripathi Avatar answered Oct 06 '22 15:10

Rahul Tripathi


Most languages which inherit from C will return a negative result if the first operand of a modulo operation is negative and the second is positive. I'm not sure why this decision was made originally. Probably closest to what processors at that time did in assembly. In any case, since then the answer to “why” is most likely “because that's what programmers who know C expect”.

The MDC Reference contains a pointer to a proposal to introduce a proper mod operator. But even that would keep the existing % operator (which they call “remainder” to better distinguish between them) and introduce a new infix word notation a mod b. The proposal dates from 2011, and I know no more recent developments in this direction.

like image 30
MvG Avatar answered Oct 06 '22 15:10

MvG