From 58da88fa6bd02abd0a8a57f8cc98d6bf84d2d91e Mon Sep 17 00:00:00 2001 From: Sebastian Schweikl Date: Sun, 10 Nov 2024 10:12:41 +0100 Subject: [PATCH 1/4] refactor(Register): add static factory function Adds a static factory function ofLength() to the Register class, instead of simulating overloading using inheritance. --- src/PQGramProfile.ts | 4 ++-- src/Register.ts | 21 +++++++++------------ test/PQGramProfile.test.ts | 12 ++++++------ test/Register.test.ts | 26 +++++++++++++------------- test/util.ts | 2 +- 5 files changed, 31 insertions(+), 34 deletions(-) diff --git a/src/PQGramProfile.ts b/src/PQGramProfile.ts index a075f63..6e4d7e8 100644 --- a/src/PQGramProfile.ts +++ b/src/PQGramProfile.ts @@ -112,12 +112,12 @@ export class PQGramProfile { requirePositiveInteger(p, q); const profile = new PQGramProfile(p + q); - const workQueue: [T, Register][] = [[tree.root, new Register(p)]]; + const workQueue: [T, Register][] = [[tree.root, Register.ofLength(p)]]; while (workQueue.length > 0) { const [r, _anc] = workQueue.shift()!; const anc = _anc.shift(tree.getLabel(r)); - let sib = new Register(q); + let sib = Register.ofLength(q); const children = tree.getChildren(r); diff --git a/src/Register.ts b/src/Register.ts index f354003..7f1275c 100644 --- a/src/Register.ts +++ b/src/Register.ts @@ -10,7 +10,10 @@ const NIL = Symbol("*"); */ type Label = string | typeof NIL; -class _Register { +/** + * A fixed-length shift register of labels. + */ +export class Register { /** * Current labels stored by the register. @@ -23,7 +26,7 @@ class _Register { * @param contents The labels with which the register is initially filled. * @protected */ - protected constructor(contents: Label[]) { + private constructor(contents: Label[]) { if (contents.length === 0) { throw new Error("empty contents"); } @@ -48,7 +51,7 @@ class _Register { const contents = [...this._contents]; contents.push(label); contents.shift(); - return new _Register(contents); + return new Register(contents); } /** @@ -57,7 +60,7 @@ class _Register { * @param that The other register to concatenate with. */ concat(that: Register): Register { - return new _Register([...this._contents, ...that._contents]); + return new Register([...this._contents, ...that._contents]); } /** @@ -66,19 +69,13 @@ class _Register { toJSON(): (string | null)[] { return this._contents.map((l) => l === NIL ? null : l); } -} - -/** - * A fixed-length shift register of labels. - */ -export class Register extends _Register { /** * Constructs a new, initially empty shift register which can hold the given fixed number of labels. * @param n The fixed length of the register. */ - constructor(n: number) { + static ofLength(n: number) { requirePositiveInteger(n); - super(Array