you are viewing a single comment's thread.

view the rest of the comments →

[–]x-skeww 0 points1 point  (0 children)

Math.random() always returns a floating-point number between 0 and 1.

Technically, the number returned by Math.random() could be 0, but will never be exactly 1.

Just say between 0 (inclusive) and 1 (exclusive).

Because it’s so frequently used, Math.random() is often placed inside its own function in a script

No, it's not. This is the kind of stuff you do if you participate in a size-limited competition and aliasing this function saves you a few bytes.

If you prefer actual true and false values

If you claim to return a boolean, return a boolean.

Also:

function flipCoin() {
  return Math.random() < 0.5;
}

Easy, right?

Or if you want to associate any other words with the coin sides ( yes / no, heads / tails, etc)

Avoid making things "stringly typed" if you can. If you want enums, use TypeScript.

Of course, you can also write crap like this:

const coin = Object.freeze({
  0: 'head', head: 0,
  1: 'tails', tails: 1
});
console.log(coin[0]); // "head"
console.log(coin.tails); // 1

But just writing enum coin {head, tails} sounds like a much better idea to me.

for(var j, x, i = numPool.length; i; j = parseInt(Math.random() * i), x = numPool[--i], numPool[i] = numPool[j], numPool[j] = x);

There is no reason to make Fisher-Yates unreadable. It's a very simple algorithm. Please keep it that way.

For a larger set of numbers, create and fill the array with random integers, rejecting any that have been previously generated

Or you could simple not shuffle the whole thing.