DEV Community

loading...

Discussion on: Dice Rolling Program

pentacular profile image
pentacular

Why not use Math.ceil?

Thread Thread
shadowtime2000 profile image
shadowtime2000 • Edited

Because some dice don't have zero while other's do. So we would need to switch on different dice.

Thread Thread
pentacular profile image
pentacular

But you're always adding one, so you'll never get zero ...

Thread Thread
shadowtime2000 profile image
shadowtime2000

Exactly. We would remove that but we would need to switch between Math.ceil and Math.floor.

Thread Thread
pentacular profile image
pentacular

Making a function more complex in order to make it simpler to do something the function does not do is not very sensible. :)

Thread Thread
shadowtime2000 profile image
shadowtime2000

What if we just did something like this:

function d(sides, hasZero = false) {
  return hasZero ? Math.ceil(Math.random() * sides) : Math.floor(Math.random() * sides);
}
Thread Thread
pentacular profile image
pentacular

If you want to generate integers in a range, you might as well just do that.

But the first thing to check are the requirements for this use case.

I believe that none of these dice include zero. :)

Forem Open with the Forem app