number-abbreviation
Version:
A simple number abbreviation tool.
62 lines (57 loc) • 2.45 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function optionsValidator(options) {
var getOtionsKeys = options ? Object.keys(options) : [];
var decimals = 1;
var suffixes = ['', 'K', 'M', 'B', 'T'];
var suffixSpace = false;
if ((getOtionsKeys == null ? void 0 : getOtionsKeys.length) > 0) {
var _options$suffixes, _options$suffixes2;
if (options != null && options.decimals && typeof (options == null ? void 0 : options.decimals) !== 'number') {
throw new Error('A number value is required!');
}
if (options != null && options.decimals && !Number.isInteger(options == null ? void 0 : options.decimals)) {
throw new Error('A interger value is required!');
}
if (options != null && options.suffixes && (options == null || (_options$suffixes = options.suffixes) == null ? void 0 : _options$suffixes.length) !== 4) {
throw new Error('The 4 suffixes indexes is required!');
}
if (options != null && options.suffixes && !options.suffixes.every(function (i) {
return typeof i === 'string';
})) {
throw new Error('An array of strings is required!');
}
return {
decimals: (options == null ? void 0 : options.decimals) || 1,
suffixes: options != null && (_options$suffixes2 = options.suffixes) != null && _options$suffixes2.length ? [''].concat(options.suffixes) : ['', 'K', 'M', 'B', 'T'],
suffixSpace: options == null ? void 0 : options.suffixSpace
};
}
return {
decimals: decimals,
suffixes: suffixes,
suffixSpace: suffixSpace
};
}
var numberAbbr = function numberAbbr(value, options) {
if (typeof value !== 'number') {
throw new Error('A number value is required!');
}
var resultOptions = optionsValidator(options);
if (value > 1000) {
var suffixIndex = Math.floor(Math.log10(value) / 3);
var scaledNumber = value / Math.pow(10, suffixIndex * 3);
var formattedNumber;
if (scaledNumber > 1 && value >= 1000) {
formattedNumber = scaledNumber.toFixed(resultOptions.decimals);
} else {
formattedNumber = scaledNumber.toFixed(0);
}
var setSuffixSpace = !!(resultOptions != null && resultOptions.suffixSpace) ? ' ' : '';
return "" + formattedNumber + setSuffixSpace + resultOptions.suffixes[suffixIndex];
} else {
return value.toString();
}
};
exports.numberAbbr = numberAbbr;
//# sourceMappingURL=number-abbreviation.cjs.development.js.map