Videos
If by "modulus" you understand the remainder of the Euclidean division as common in mathematics, the % operator is not the modulo operator. It rather is called the remainder operator, whose result always has the same sign as the dividend. (In Haskell, the rem function does this).
This behaviour is pretty common amongst programming languages, notably also in C and Java from which the arithmetic conventions of JavaScript were inspired.
Note that while in most languages, ‘%’ is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. For two values of the same sign, the two are equivalent, but when the dividend and divisor are of different signs, they give different results. To obtain a modulo in JavaScript, in place of a % n, use ((a % n ) + n ) % n
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
The problem with % is that it is a remainder operator with truncated division, not a modulo one with floored division. When the divisor (i-1) becomes negative, so does the result. You can use
if (--i < 0) i = stuff.length - 1;
or
i = (i + stuff.length - 1) % stuff.length;
instead (which only work for input values of i in the expected range, though)
If you want next() to increment i between 0 and 2 and prev() to decrement between 2 and 0 you can use the following:
next() {
this.props.dispatch(increaseCounter());
i = Math.min(i + 1, stuff.length - 1);
}
prev() {
this.props.dispatch(decreaseCounter());
i = Math.max(i - 1, 0);
}
For some number y and some divisor x compute the quotient (quotient)[1] and remainder (remainder) as:
const quotient = Math.floor(y/x);
const remainder = y % x;
Example:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1] The integer number resulting from the division of one number by another
I'm no expert in bitwise operators, but here's another way to get the whole number:
var num = ~~(a / b);
This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.
This seems correct as well:
var num = (a / b) >> 0;
Note: Only use ~~ as a substitution for Math.trunc() when you are confident that the range of input falls within the range of 32-bit integers.