There aren't any built in ways of doing it, but I have a couple functions that might help you: const expressionMax = (txt) => {
const tokenize = /(\d+d\d+|\d+|\+|-)/ig;
const dieparts = /^(\d+)?d(\d+)$/i;
const ops = {
'+': (m,n) => m+n,
'-': (m,n) => m-n
};
let op = '+';
return (txt.replace(/\s+/g,'').match(tokenize)||[]).reduce((m,t)=>{
let matches = t.match(dieparts);
if(matches){
return ops[op](m,[...Array(parseInt(matches[1])||1)].reduce(m=>m+(parseInt(matches[2])),0));
} else if(/^\d+$/.test(t)){
return ops[op](m,parseInt(t));
} else {
op = t;
return m;
}
},0);
};
const expressionMin = (txt) => {
const tokenize = /(\d+d\d+|\d+|\+|-)/ig;
const dieparts = /^(\d+)?d(\d+)$/i;
const ops = {
'+': (m,n) => m+n,
'-': (m,n) => m-n
};
let op = '+';
return (txt.replace(/\s+/g,'').match(tokenize)||[]).reduce((m,t)=>{
let matches = t.match(dieparts);
if(matches){
return ops[op](m,[...Array(parseInt(matches[1])||1)].reduce(m=>m+1,0));
} else if(/^\d+$/.test(t)){
return ops[op](m,parseInt(t));
} else {
op = t;
return m;
}
},0);
};
I'm pretty sure they work right... at a minimum, they can be a jumping off point.