|
- import Big from 'big.js'
- import ConverterStream from './ConverterStream'
- import { ReadStreamOptions, ConvertOptions, NumberSystem, Digit } from './common'
-
- export default class Converter {
- constructor(private readonly system: NumberSystem, private options: ConvertOptions) {}
-
- public convert = (value: string | number | bigint): string => {
- let converted: string[] = []
- const valueStr = value as string
- switch (typeof value!) {
- case 'string':
- // TODO bail out when exponent is too large!
- try {
- return this.convert(BigInt(new Big(valueStr).toFixed()))
- } catch (e) {}
- return this.convert(BigInt(valueStr))
- case 'number':
- return this.convert(BigInt(value as number))
- 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' } = this.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.')
- }
-
- public readStream = (streamOptions: ReadStreamOptions): ConverterStream => {
- return new ConverterStream(this.convert, streamOptions)
- }
- }
|