Page 66 - JavaScript
P. 66

Remainder / Modulus (%)


        The remainder / modulus operator (%) returns the remainder after (integer) division.


         console.log( 42 %  10); //  2
         console.log( 42 % -10); //  2
         console.log(-42 %  10); // -2
         console.log(-42 % -10); // -2
         console.log(-40 %  10); // -0
         console.log( 40 %  10); //  0




        This operator returns the remainder left over when one operand is divided by a second operand.
        When the first operand is a negative value, the return value will always be negative, and vice
        versa for positive values.

        In the example above, 10 can be subtracted four times from 42 before there is not enough left to
        subtract again without it changing sign. The remainder is thus: 42 - 4 * 10 = 2.

        The remainder operator may be useful for the following problems:


            1.  Test if an integer is (not) divisible by another number:


                x % 4 == 0 // true if x is divisible by 4
                x % 2 == 0 // true if x is even number
                x % 2 != 0 // true if x is odd number


              Since 0 === -0, this also works for x <= -0.

            2.  Implement cyclic increment/decrement of value within [0, n) interval.


        Suppose that we need to increment integer value from 0 to (but not including) n, so the next value
        after n-1 become 0. This can be done by such pseudocode:


         var n = ...; // given n
         var i = 0;
         function inc() {
             i = (i + 1) % n;
         }
         while (true) {
             inc();
             // update something with i
         }


        Now generalize the above problem and suppose that we need to allow to both increment and
        decrement that value from 0 to (not including) n, so the next value after n-1 become 0 and the
        previous value before 0 become n-1.


         var n = ...; // given n
         var i = 0;
         function delta(d) { // d - any signed integer
             i = (i + d + n) % n; // we add n to (i+d) to ensure the sum is positive




        https://riptutorial.com/                                                                               23
   61   62   63   64   65   66   67   68   69   70   71