@aplus-frontend/utils
Version:
Utils for Aplus frontend team.
81 lines (80 loc) • 2.97 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const lodashEs = require("lodash-es");
const Decimal = require("decimal.js");
function isNumeric(value) {
return !isNaN(parseFloat(value)) && lodashEs.isFinite(Number(value));
}
function toFixed(value, precision = 2) {
if (!isNumeric(value)) return value;
return new Decimal(value).toFixed(precision).toString();
}
function toSignificantDigits(value, precision = 2) {
if (!isNumeric(value) || precision <= 0) return value;
return new Decimal(value).toSignificantDigits(precision).toString();
}
function toThousand(value, precision = 2, type = "fixed") {
if (!isNumeric(value)) return value;
const toList = {
fixed: toFixed,
significantDigits: toSignificantDigits
};
const numberValue = toList[type](value, precision).toString();
return numberValue.split(".").map((item, index) => {
if (index === 0) {
return item.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,");
} else {
return item;
}
}).join(".");
}
function toPercent(value, precision = 2, type = "fixed") {
if (!isNumeric(value)) return value;
if (precision <= 0) {
return `${new Decimal(value).mul(new Decimal(100)).toFixed(0).toString()}%`;
}
return `${new Decimal(value).mul(new Decimal(100))[`to${type.charAt(0).toUpperCase()}${type.slice(1)}`](precision).toString()}%`;
}
function addNumberAtom(a, b) {
if (!isNumeric(a) || !isNumeric(b)) return void 0;
return new Decimal(a).add(new Decimal(b));
}
function subNumberAtom(a, b) {
if (!isNumeric(a) || !isNumeric(b)) return void 0;
return new Decimal(a).sub(new Decimal(b));
}
function mulNumberAtom(a, b) {
if (!isNumeric(a) || !isNumeric(b)) return void 0;
return new Decimal(a).mul(new Decimal(b));
}
function divNumberAtom(a, b) {
if (!isNumeric(a) || !isNumeric(b)) return void 0;
return new Decimal(a).div(new Decimal(b));
}
function addNumber(...args) {
return args.every(isNumeric) ? args.reduce((a, b) => addNumberAtom(a.toString(), b.toString())) : void 0;
}
function subNumber(...args) {
return args.every(isNumeric) ? args.reduce((a, b) => subNumberAtom(a.toString(), b.toString())) : void 0;
}
function mulNumber(...args) {
return args.every(isNumeric) ? args.reduce((a, b) => mulNumberAtom(a.toString(), b.toString())) : void 0;
}
function divNumber(...args) {
return args.every(isNumeric) ? args.reduce((a, b) => divNumberAtom(a.toString(), b.toString())) : void 0;
}
exports.addNumber = addNumber;
exports.divNumber = divNumber;
exports.isNumeric = isNumeric;
exports.mulNumber = mulNumber;
exports.subNumber = subNumber;
exports.toFixed = toFixed;
exports.toPercent = toPercent;
exports.toSignificantDigits = toSignificantDigits;
exports.toThousand = toThousand;
Object.keys(Decimal).forEach((k) => {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: () => Decimal[k]
});
});
;