Reputation: 403
inspecting some code, I found the following random integer generator function:
function randomInt(min, max) {
return min ? min : min = 0,
max ? max : max = 1,
0 | Math.random() * (max - min + 1) + min
}
Comparing it with the equivalent function at MDN:
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
I understand that the first creates and integer with max
included, and that it checks for values or assign them defaults to min
and max
but I don't understand how it returns an integer and not a float without the Math.floor()
method.
Is it achieved using 0 | Math.random() * (max - min + 1) + min
expression? If so, how?
Upvotes: 3
Views: 70
Reputation: 149020
The result is converted to an integer with the |
operator, which is the bitwise OR. From MDN, the first step in computing the result is:
The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
And because you're ORing with 0, this operation will not change the value of the result (other than the previously mentioned conversion).
Upvotes: 4
Reputation: 887657
0 |
is a bitwise operation.
It has no effect on the value (ORing with zero returns the original value), but, like all bitwise operations, it truncates to an integer (bitwise operations make no sense on non-integers).
Upvotes: 1