-
Notifications
You must be signed in to change notification settings - Fork 0
/
dice.js
107 lines (96 loc) · 2.73 KB
/
dice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
( function (root, factory) {
/* istanbul ignore next */
if (typeof define === 'function') {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Dice = factory();
}
} (this, function () {
'use strict';
var diceNotation = /(\d+)[dD](\d+)(.*)$/i;
var modifier = /([+-])(\d+)/;
function compressNotation (notation) {
return notation.trim().replace(/\s+/g, '');
}
function validNumber (n, err) {
n = Number(n);
if (Number.isNaN(n) || !Number.isInteger(n) || n < 1) {
throw new Error(err);
}
return n;
}
function parse (notation) {
var roll = compressNotation(notation).match(diceNotation), mod = 0;
var msg = 'Invalid notation: ' + notation + '';
/* istanbul ignore next */
if (roll.length < 3) {
throw new Error(msg);
}
if (roll[3] && modifier.test(roll[3])) {
var modParts = roll[3].match(modifier);
var basicMod = validNumber(modParts[2], msg);
if (modParts[1].trim() === '-') {
basicMod *= -1;
}
mod = basicMod;
}
roll[1] = validNumber(roll[1], msg);
roll[2] = validNumber(roll[2], msg);
return {
number : roll[1],
type : roll[2],
modifier : mod
};
}
function roll (a, b, rnd) {
if (!rnd) {
rnd = Math.random;
}
var rolls = [];
var result = 0;
for (var i = 0; i < a; i++) {
var die = 0;
die = Math.floor(rnd() * b) + 1;
result += die;
rolls.push(die);
}
return {
rolls : rolls,
result : result
};
}
function rollMe (a, b, rnd) {
var msg = 'Invalid dice values.', toRoll = {};
if (typeof a === 'string') {
toRoll = parse(a);
} else if (typeof a === 'number') {
toRoll = {
number : validNumber(a, msg),
type : validNumber(b, msg),
modifier : 0
};
} else {
throw new Error(msg);
}
if (typeof b === 'function') {
rnd = b;
}
var rolled = roll(toRoll.number, toRoll.type, rnd);
rolled.result += toRoll.modifier;
Object.assign(toRoll, rolled);
return toRoll;
}
function Dice (a, b, rnd) {
return rollMe(a, b, rnd).result;
}
function detailedRoll (a, b, rnd) {
return rollMe(a, b, rnd);
}
Object.assign(Dice, {
parse : parse,
detailed : detailedRoll
});
return Dice;
}));