|
- import NumberSystem from './NumberSystem'
- import ConverterStream from './ConverterStream'
- import { ReadStreamOptions, ConvertOptions } from './common'
-
- export default class Converter {
- constructor(private readonly system: NumberSystem) {}
-
- convert(value: string | number | bigint, options: ConvertOptions) {
- let converted: string[] = []
- switch (typeof value!) {
- case 'string':
- return ''
- case 'bigint':
- case 'number':
- let current = value as number
- let thousandPower = 0
- while (current > 0) {
- const hundreds = Math.floor((current % 1000) / 100)
- const tens = Math.floor((current % 100) / 10)
- const ones = Math.floor(current % 10)
- if (!(ones === 0 && tens === 0 && hundreds === 0)) {
- if (thousandPower > 0) {
- const { scale = 'short' } = options
- converted.unshift(this.system.getKiloName[scale!]!(thousandPower))
- }
- converted.unshift(this.system.getKiloCount(hundreds, tens, ones))
- }
-
- thousandPower = thousandPower + 1
- current = Math.floor(current / 1000)
- }
- 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 })
- }
- }
|