|
- import { Transform } from 'stream'
- 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
- }
-
- _transform(chunk: Buffer, _encoding: BufferEncoding, callback: Function) {
- const { scale, encoding } = this.options
-
- const [ones = 0, tens = 0, hundreds = 0] = chunk
- .toString(encoding!)
- .split('')
- .filter((s: string) => /[0-9]/.test(s))
- .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 > 0n) {
- kiloName = this.system.getKiloName[scale!]!(this.thousandPower)
- }
- 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()
- }
- }
|