Reputation: 1
I want to write a dice function that accepts multiple different inputs and can make sense of each of them, for example: "1d20"
, "1,20"
, and "20"
.
I want to be able to pass either a string similar to the first two examples or the numbers as separate parameters, which is working well. The problem occurs when I try to pass it the single number. I would prefer the optional parameter to come first.
function dice(quan, top) {
var ct = 0, upd = 0;
if (top === undefined) {
upd = Math.max(quan.indexOf(","), quan.indexOf("d"));
if (upd < 1) { //pass single parameter, eg. '20' for 1d20. Not working
top = quan;
quan = 1;
} else {
top = quan.slice(upd + 1, quan.length + 1);
quan = quan.slice(0, upd);
}
}
for (ct = 0, upd = 0; ct < quan; ct++) {
upd += Math.ceil(Math.random() * top);
}
return upd;
}
Upvotes: 0
Views: 263
Reputation: 1
Using arrays instead like suggested by @Nine Scholz, this is what I've got:
function dice(val) {
var ct = 0, upd = 0, str, top, quan;
if (val + 0 == val) {
quan = 1;
top = val;
} else {
str = val.replace("d",",").split(",");
quan = str[0];
top = str[1];
}
if (isNaN(quan)||isNaN(top)) {
return "NaN";
}
for (ct = 0,upd = 0; ct < quan; ct++) {
upd += Math.ceil(Math.random() * top);
}
return upd;
}
Upvotes: 0
Reputation: 386680
You could split by d
or comma and map the numbers and check the length.
function getParts(string) {
var p = string.split(/[d,]/).map(Number);
return p.length === 1
? [1, p[0]]
: p;
}
console.log(["1d20", "1,20", "20"].map(getParts));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1