dice-roller / rpg-dice-roller

An advanced JS based dice roller that can roll various types of dice and modifiers, along with mathematical equations.
https://dice-roller.github.io/documentation
MIT License
243 stars 59 forks source link

Support ternary operator #240

Open xremming opened 2 years ago

xremming commented 2 years ago

Is your feature request related to a problem? Please describe. In the tool I'm writing currently I use mustache for user side templating and this lib to "evaluate" the values. For some expression it would be easier and cleaner to write and use them if this lib would support ternary operations.

Describe the solution you'd like Support writing a ? b : c which returns b if a is non-zero and c if a is zero. With this the comparison operators should also work with just naked numbers so that the following expression would also work 1>0 ? 100 : 0.

Describe alternatives you've considered I can always write my own parser on top of this lib and I might have to do that at some point anyways. 😅

GreenImp commented 2 years ago

I like this!

Internally, we use MathJs, which does support ternary operators. So it should be possible to add some grammar for it, in the parser file.

Happy for PRs 🙂

xremming commented 2 years ago

I've been on quite a roll with my own project and this would become very handy for me, so let's see if I will make PR. 🤔

GreenImp commented 2 years ago

Awesome!

Ourt of interest, are you able to provide any real world uses for the ternary?

I can think of things like this:

// Roll a d6 where greater than or equal to 5 is success
// If success, then return 2, otherwise return 1
1d6>=5 ? 2 : 1

Or perhaps even:

1d6>=5 ? 2d10 : 2d3

Maybe even something like this (Although it could conflict with some modifiers):

(2d10 * 3) > 250 ? 300 : 100
jacksontheel commented 2 years ago

I can imagine a lot of benefits with this, checking for success before performing another roll is a very common action in a lot of tabletop rpgs. Something like checking if an attack hits in dnd 5e with (d20>10) ? d8 : 0.

Unfortunately, with how comparisons are implemented, something like (d20+4>10) does not work. However, that seems outside the scope of this issue.

I went ahead and made the quick change necessary and put up a pull request.