UNPKG

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.

84 lines (83 loc) 2.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseConverter = void 0; const formatUtils_1 = require("../utils/formatUtils"); const validationUtils_1 = require("../utils/validationUtils"); class BaseConverter { constructor() { this.wordCache = new Map(); this.scales = []; this.customUnits = {}; this.customScales = {}; } setCustomMappings(config) { if (!(0, validationUtils_1.validateCustomMappings)(config)) { throw new Error('Input must contain only valid digits'); } this.customUnits = config.units ?? {}; this.customScales = config.scales ?? {}; } getWordMapping(num, lang) { if (this.customUnits[num]?.[lang]) { return this.customUnits[num][lang]; } const mapping = this.wordCache.get(num); if (!mapping) { throw new Error('Input must contain only valid digits'); } return mapping[lang]; } getScaleName(value, lang) { // First check custom scales const numValue = Number(value); if (this.customScales[numValue]?.[lang]) { return this.customScales[numValue][lang]; } const scale = this.scales.find(s => s.value === value); if (!scale) { throw new Error('Input must contain only valid digits'); } return scale.names[lang]; } processLargeNumber(num, words, config) { if (num === 0n) return; // Find largest applicable scale by iterating once let currentScale; for (const scale of this.scales) { if (num >= scale.value) { currentScale = scale; break; } } if (!currentScale) { // Handle numbers less than smallest scale (100) if (num <= 99n) { words.push(this.getWordMapping(Number(num), config.lang)); } return; } const quotient = num / currentScale.value; const remainder = num % currentScale.value; // Process quotient recursively only if > 99 if (quotient > 99n) { this.processLargeNumber(quotient, words, config); } else { words.push(this.getWordMapping(Number(quotient), config.lang)); } words.push(this.getScaleName(currentScale.value, config.lang)); // Process remainder only if non-zero if (remainder > 0n) { this.processLargeNumber(remainder, words, config); } } formatResult(words, config) { const formatted = (0, formatUtils_1.formatWords)(words); if (config.isCurrency) { return (0, formatUtils_1.formatCurrencyAmount)(formatted, config.currency, config.lang); } return formatted; } } exports.BaseConverter = BaseConverter;