## DEV Community is a community of 647,226 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Dice Rolling Program

pentacular • Edited

You repeat yourself a lot. :)

The following technique may help avoid that.

``````const d = (sides) =>
() => Math.ceil(Math.random() * sides);

const d20 = d(20);
const d12 = d(12);

console.log(d20());
``````

Here d is a function which generates parameterized functions by using lexical closure.

You don't need to have a function that returns another function. You can simplify it to this:

``````function d(sides) {
return Math.floor(Math.random() * sides + 1);
}
``````

And use it with this:

``````console.log(d(20));
``````
pentacular

That's true, but his code wants to call functions directly.

Also, why are you adding 1 and then flooring?

I am adding one because `Math.random()` returns a float between 0 and 1, but it never includes 1, so you could never get 20 without adding 1.

pentacular

Why not use Math.ceil?

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

pentacular

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

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

pentacular

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

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);
}
``````