@mateo-wallace/rpg-dice-js
Version:
Npm package that allows users to roll dice with all math and various forms of response
178 lines (177 loc) • 9.3 kB
JavaScript
;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _mathjs = require("mathjs");
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var rng = function rng(sides) {
if (sides === 1) return 1;else return _crypto["default"].randomInt(1, sides + 1);
};
var spaceNormalizer = function spaceNormalizer(userInput, separators) {
var spaceNormalize = "";
if (userInput) {
spaceNormalize = userInput.replaceAll(" ", "").toLowerCase();
separators.forEach(function (separator) {
var rg = new RegExp("\\".concat(separator), "g");
spaceNormalize = spaceNormalize.replace(rg, " ".concat(separator, " "));
});
}
return spaceNormalize;
};
var diceNoInput = function diceNoInput(defaultDie, isBoldCrit, boldWrapper) {
var sum = rng(defaultDie);
var sumTotal = "".concat(sum);
var critTotal = "".concat(sum * 2);
var total = "d".concat(defaultDie, " (").concat(isBoldCrit ? sum === 1 || sum === defaultDie ? "".concat(boldWrapper[0]).concat(sum).concat(boldWrapper[1]) : sum : sum, ")");
return {
sumTotal: sumTotal,
critTotal: critTotal,
total: total
};
};
var diceInputMathLogic = function diceInputMathLogic(messageWords, separators) {
var resultWords = [];
messageWords.forEach(function (word) {
if (word.includes("d")) {
var sides = 20; // !roll 20
var rolls = 1;
if (!isNaN(word[0] / 1) && word.includes("d")) {
var _word$split$map = word.split("d").map(Number);
var _word$split$map2 = _slicedToArray(_word$split$map, 2);
rolls = _word$split$map2[0];
sides = _word$split$map2[1];
} else if (word[0] === "d") sides = Number(word.slice(1));else sides = NaN;
if (isNaN(sides) || isNaN(rolls)) throw new Error("Invalid Dice Input");
if (rolls > 1) {
var rollResults = Array.from({
length: rolls
}, function () {
return rng(sides);
});
var sum = rollResults.reduce(function (a, b) {
return a + b;
});
rollResults.push(sum);
resultWords.push(rollResults);
} else resultWords.push(rng(sides));
} else if (separators.includes(word) || !isNaN(word / 1)) resultWords.push(word);else throw new Error("Invalid Dice Input");
});
return resultWords;
};
var diceInput = function diceInput(messageWords, resultWords, separators, isBoldCrit, boldWrapper) {
var result = [];
var sum = [];
var crit = [];
var _loop = function _loop(i) {
var boldCrit = isBoldCrit ? resultWords[i] == 1 || resultWords[i] == messageWords[i].split("d")[1] / 1 ? "".concat(boldWrapper[0]).concat(resultWords[i]).concat(boldWrapper[1]) : resultWords[i] : resultWords[i];
if (messageWords[i].includes("d") && !isNaN(resultWords[i] / 1)) {
sum.push(resultWords[i]);
crit.push(resultWords[i] * 2);
result.push("".concat(messageWords[i], " (").concat(boldCrit, ")"));
} else if (separators.includes(resultWords[i]) || !isNaN(resultWords[i] / 1)) {
sum.push(resultWords[i]);
crit.push(resultWords[i]);
result.push("".concat(resultWords[i]));
} else if (Array.isArray(resultWords[i])) {
var popped = resultWords[i].pop();
sum.push(popped);
crit.push(popped * 2);
var arr = resultWords[i].map(function (item, j) {
var boldCritArr = isBoldCrit ? item == 1 || item == messageWords[i].split("d")[1] / 1 ? "".concat(boldWrapper[0]).concat(item).concat(boldWrapper[1]) : item : item;
return j === 0 ? "".concat(boldCritArr) : " ".concat(boldCritArr);
});
result.push("".concat(messageWords[i], " (").concat(arr, ")"));
}
};
for (var i = 0; i < resultWords.length; i++) {
_loop(i);
}
var total = result.join(" ");
var sumTotal = (0, _mathjs.evaluate)(sum.join(" "));
var critTotal = (0, _mathjs.evaluate)(crit.join(" "));
return {
total: total,
sumTotal: sumTotal,
critTotal: critTotal
};
};
var splitFilterJoin = function splitFilterJoin(total, depth) {
var s = total.split(/(?!\(.*)\s(?![^(]*?\))/g);
var sf = s.filter(function (value) {
return !value.includes("d");
});
var sfj = sf.join(" ");
if (depth === 1) return s;
if (depth === 2) return sf;
if (depth === 3) return sfj;
};
var responseFilter = function responseFilter(response, responseOptions) {
var onlyTrueObj = {};
for (var key in responseOptions) {
if (responseOptions[key] === true) {
onlyTrueObj[key] = response[key];
}
}
return onlyTrueObj;
};
var rollMethod = function rollMethod(_ref) {
var userInput = _ref.userInput,
isBoldCrit = _ref.isBoldCrit,
defaultDie = _ref.defaultDie,
boldWrapper = _ref.boldWrapper,
responseOptions = _ref.responseOptions;
var separators = ["+", "-", "*", "/"];
var message = spaceNormalizer(userInput, separators);
var messageWords = message ? message.split(" ") : [];
var total, sumTotal, critTotal;
if (!messageWords.length) {
var data = diceNoInput(defaultDie, isBoldCrit, boldWrapper);
sumTotal = data.sumTotal;
critTotal = data.critTotal;
total = data.total;
} else {
try {
var resultWords = diceInputMathLogic(messageWords, separators);
var _data = diceInput(messageWords, resultWords, separators, isBoldCrit, boldWrapper);
sumTotal = _data.sumTotal;
critTotal = _data.critTotal;
total = _data.total;
} catch (err) {
return {
ok: false,
input: userInput,
message: "Invalid Input",
err: err
};
}
}
var responseLayout = {
ok: true,
input: message,
result: total,
total: sumTotal,
resultNoDice: splitFilterJoin(total, 3),
prefab: "Input: ".concat(message, " | Result: ").concat(total, " | Total: ").concat(sumTotal),
inputArray: messageWords,
resultArray: splitFilterJoin(total, 1),
resultNoDiceArray: splitFilterJoin(total, 2),
totalCrit: critTotal
};
var response = responseFilter(responseLayout, responseOptions);
return _objectSpread({}, response);
};
var _default = exports["default"] = rollMethod;