|
- import ConverterStream from './ConverterStream'
- import { ReadStreamOptions, ConvertOptions, NumberSystem, Digit } from './common'
-
- export default class Converter {
- constructor(private readonly system: NumberSystem) {}
-
- public convert = (value: string | number | bigint, options: ConvertOptions): string => {
- let converted: string[] = []
- switch (typeof value!) {
- case 'string':
- case 'number':
- return this.convert(BigInt(value), options)
- case 'bigint':
- let current = value as bigint
- let thousandPower = 0n
- while (current > 0n) {
- const hundreds = Number(((current % 1000n) / 100n) % 10n) as Digit
- const tens = Number(((current % 100n) / 10n) % 10n) as Digit
- const ones = Number(current % 10n) as Digit
-
- let kiloName: string | undefined
- let kiloCount: string
- if (!(ones === 0 && tens === 0 && hundreds === 0)) {
- if (thousandPower > 0n) {
- const { scale = 'short' } = options
- kiloName = this.system.getKiloName[scale!]!(thousandPower)
- }
- kiloCount = this.system.getKiloCount(hundreds, tens, ones)
- converted.unshift(this.system.joinKilo(kiloCount, kiloName))
- }
-
- thousandPower = thousandPower + 1n
- current = current / 1000n
- }
- return converted.join(' ')
- default:
- break
- }
- throw TypeError('Invalid argument passed to value.')
- }
-
- readStream(options: ReadStreamOptions): ConverterStream {
- const { scale = 'short', encoding = 'utf-8' } = options
- return new ConverterStream(this.system, { scale, encoding })
- }
- }
|