JS module used for evaluating standard dice notation expressions. The module can actually evaluate simple mathematical expressions, consisting of integers and operators +
, -
, *
, /
, as well as sub-expressions enclosed in parentheses. To (mostly) comply with standard dice notation, an additional operator is implemented: d
. This operator takes the form AdX
or dX
, where A
is the number of rolls of X
-sided die.
5d6 -> rolls a 6-sided die, 5 times
5d6 + 10 -> rolls a 6-sided die, 5 times, and adds 10 to the result.
5d6 / 2 -> rolls a 6-sided die, 5 times, and divides the result by 2.
(10*10)d(10*10) -> rolls a (10*10)-sided die, (10*10) times.
Expressions are passed as plain strings to the module, which returns a number. The evaluation may throw.
const evaluate = require("dice-roll-eval");
const result = evaluate("5d6 + 10");
// ...
evaluate
also takes two optional parameters, limit
and rng
.
limit
: A dice roll like 5d6
will roll a 6-sided die 5 times. These rolls have to be executed in sequence, and in this library, that is done inside of a while loop. This stalls the event loop. To ensure that a user can't do something like (1/0)d6
(i.e. roll a D6 Infinity times), you can set the maximum number of sequential rolls. The default is 10.
rng
: The random number generation function, which must have the following signature:
(min: number, max: number) => number;
The min
and max
numbers specify the range in which values should be generated, e.g. the call YOUR_RNG_FUNCTION(10, 2000)
should generate a number within the range <10; 2000>. This parameter exists so that you can provide your own RNG implementation, such as a Mersenne Twister. The default implementation uses Math.random
and can be found here.
Tests are built with Jest.
$ yarn test
Built for supi-core.
This was my excuse to learn more about parsing strings. Yes, it is slightly overkill... :)