|
|
@@ -1,47 +1,26 @@ |
|
|
|
import { Transform } from 'stream' |
|
|
|
import { Digit, NumberSystem, ReadStreamOptions } from './common' |
|
|
|
import { StreamOptions } from './common' |
|
|
|
|
|
|
|
export default class ConverterStream extends Transform { |
|
|
|
private thousandPower: bigint = 0n |
|
|
|
private bigintBuffer: bigint = 0n |
|
|
|
|
|
|
|
private buffer = Buffer.from([]) |
|
|
|
|
|
|
|
constructor(private readonly system: NumberSystem, private readonly options: ReadStreamOptions) { |
|
|
|
constructor( |
|
|
|
private readonly converter: (value: string | number | bigint) => string, |
|
|
|
readonly options: StreamOptions, |
|
|
|
) { |
|
|
|
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 |
|
|
|
let chunkStr = chunk.toString(this.options.encoding) |
|
|
|
// we might run out of allocation for bigints? |
|
|
|
this.bigintBuffer *= 10n ** BigInt(chunkStr.length) |
|
|
|
this.bigintBuffer += BigInt(chunkStr) |
|
|
|
callback() |
|
|
|
} |
|
|
|
|
|
|
|
_flush(callback: Function) { |
|
|
|
const { encoding } = this.options |
|
|
|
this.push(this.buffer, encoding) |
|
|
|
this.push(this.converter(this.bigintBuffer), this.options.encoding) |
|
|
|
callback() |
|
|
|
} |
|
|
|
} |