diff --git a/src/ConverterStream.ts b/src/ConverterStream.ts index 88e7327..8e307a3 100644 --- a/src/ConverterStream.ts +++ b/src/ConverterStream.ts @@ -4,6 +4,8 @@ import { Digit, NumberSystem, ReadStreamOptions } from './common' export default class ConverterStream extends Transform { private thousandPower: bigint = 0n + private buffer = Buffer.from([]) + constructor(private readonly system: NumberSystem, private readonly options: ReadStreamOptions) { super() this.thousandPower = 0n @@ -16,29 +18,30 @@ export default class ConverterStream extends Transform { .toString(encoding!) .split('') .filter((s: string) => /[0-9]/.test(s)) - .map((d: string) => Number(d)) // todo use encoding + .map((d: string) => Number(d) as Digit) // todo use encoding + + let kiloName: string | undefined + let kiloCount: string if (!(ones === 0 && tens === 0 && hundreds === 0)) { - if (this.thousandPower > 0) { - this.push( - this.system.getKiloName[scale!]!(this.thousandPower) - .split('') - .reverse() - .join(''), - ) - this.push(' ') + if (this.thousandPower > 0n) { + kiloName = this.system.getKiloName[scale!]!(this.thousandPower) } - this.push( - this.system - .getKiloCount(hundreds as Digit, tens as Digit, ones as Digit) - .split('') - .reverse() - .join(''), - ) - this.push(' ') + kiloCount = this.system.getKiloCount(hundreds, tens, ones) + this.buffer = Buffer.concat([ + Buffer.from(this.system.joinKilo(kiloCount, kiloName), encoding), + Buffer.from(' ', encoding), + this.buffer, + ]) } this.thousandPower = this.thousandPower + 1n callback() } + + _flush(callback: Function) { + const { encoding } = this.options + this.push(this.buffer, encoding) + callback() + } }