@daysnap/utils
Version:
24 lines (20 loc) • 1.44 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/parseDecimalString.ts
function parseDecimalString(val, options = {}) {
const { precision = 0, allowNegativeNumber = true } = options;
const reg = new RegExp(
`^${allowNegativeNumber ? "-?" : ""}(0|[1-9]\\d*)?${+precision === 0 ? "" : `(\\.?\\d{0,${precision}})?`}`,
"g"
);
val = _nullishCoalesce(_optionalChain([val, 'access', _ => _.match, 'call', _2 => _2(reg), 'optionalAccess', _3 => _3[0]]), () => ( ""));
if (val.startsWith("-00")) {
val = `-0`;
} else if (val.startsWith("-.")) {
val = "-";
} else if (val.startsWith(".")) {
val = "";
} else if (val.startsWith("0") && !val.startsWith("0.") && val.length > 1) {
val = `${+val}`;
}
return val;
}
exports.parseDecimalString = parseDecimalString;