From b23eb4d7c011a6288aa9f6491a8e036bad775b65 Mon Sep 17 00:00:00 2001 From: Eugene Date: Sat, 6 Dec 2025 12:30:06 +0300 Subject: [PATCH] add spaces between bits group --- src/bitmap.test.ts | 4 ++-- src/bitmap.ts | 13 +++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/bitmap.test.ts b/src/bitmap.test.ts index 7989f31..f756f24 100644 --- a/src/bitmap.test.ts +++ b/src/bitmap.test.ts @@ -210,11 +210,11 @@ describe("Bitmap", () => { bitmap.set(i); } - const resultString = "0101010101010101"; + const resultString = "01010101 01010101"; expect(bitmap.toString()).toEqual(resultString); expect(String(bitmap)).toEqual(resultString); - expect(`bitmap debug: ${bitmap}`).toEqual("bitmap debug: 0101010101010101") + expect(`bitmap debug: ${bitmap}`).toEqual(`bitmap debug: ${resultString}`) const bitmap2 = Bitmap.fromString(bitmap.toString()); expect(bitmap2.toString()).toEqual(bitmap.toString()); diff --git a/src/bitmap.ts b/src/bitmap.ts index b738f12..c16ef37 100644 --- a/src/bitmap.ts +++ b/src/bitmap.ts @@ -73,7 +73,9 @@ export class Bitmap { * @returns {string} Binary string representing the full contents of the bitmap. */ public toString(): string { - return Array.from(this.bits).map((x) => x.toString(2).padStart(8, '0')).join('') + return Array.from(this.bits) + .map(x => x.toString(2).padStart(8, '0')) + .join(' '); } /** @@ -86,14 +88,17 @@ export class Bitmap { * @throws {Error} If the input length is not divisible by 8. */ static fromString(s: string): Bitmap { - if (s.length % 8 !== 0) { + // allow "00000001 00000010", "0000000100000010", etc. + const cleaned = s.replace(/\s+/g, ''); + + if (cleaned.length % 8 !== 0) { throw new Error("Bitmap string must be aligned to bytes (len % 8 == 0)"); } - const bytes = new Uint8Array(s.length / 8); + const bytes = new Uint8Array(cleaned.length / 8); for (let i = 0; i < bytes.length; i++) { - const byteStr = s.slice(i * 8, i * 8 + 8); + const byteStr = cleaned.slice(i * 8, i * 8 + 8); bytes[i] = parseInt(byteStr, 2); }