digit-to-words-nepali
Version:
A comprehensive TypeScript library for converting numbers to words in English and Nepali languages. Supports numbers up to 10^39 (Adanta Singhar), currency formatting, decimal handling, and BigInt. Zero dependencies, fully tested.
37 lines (36 loc) • 1.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unicodeToEnglishNumber = exports.digitMap = void 0;
exports.digitMap = {
'0': '०', '1': '१', '2': '२', '3': '३', '4': '४',
'5': '५', '6': '६', '7': '७', '8': '८', '9': '९'
};
// Reverse mapping for Nepali to English digits
const nepaliToEnglishDigitMap = Object.fromEntries(Object.entries(exports.digitMap).map(([en, ne]) => [ne, en]));
/**
* Converts a string of Nepali unicode digits (०-९) to a JavaScript number.
* Throws if input is not a valid Nepali digit string or exceeds safe integer.
*/
const unicodeToEnglishNumber = (numStr) => {
const DIGIT_REGEX_NEPALI = /^[०-९]+$/;
if (typeof numStr !== "string" || numStr.length === 0) {
throw new Error("Input must be a non-empty string");
}
if (!DIGIT_REGEX_NEPALI.test(numStr)) {
throw new Error("Input must contain only Nepali digits (०-९)");
}
let englishStr = "";
for (const char of numStr) {
const en = nepaliToEnglishDigitMap[char];
if (en === undefined) {
throw new Error(`Invalid Nepali digit: ${char}`);
}
englishStr += en;
}
const num = Number(englishStr);
if (!Number.isSafeInteger(num)) {
throw new Error("Number exceeds maximum safe integer value");
}
return num;
};
exports.unicodeToEnglishNumber = unicodeToEnglishNumber;