Search code examples
javascriptjquerymathmodulonegative-number

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.


Solution

  • You can try this :p-

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

    Check out this