Skip to content

Commit 2451f43

Browse files
committed
feat: add comments and improve decensor performance
1 parent cea8ddb commit 2451f43

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/format.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,27 @@ export class FormatConverter {
135135
}
136136

137137
decensor(note_text: string, mask: string, replacements: string[], escape: boolean): string {
138-
let i = 0;
139-
return note_text.replace(new RegExp(mask, 'g'), (): string => {
140-
let replacement: string = replacements[i++];
138+
let index = 0;
139+
140+
// note_text example: "The OBSTOANKICODEDISPLAY is worth OBSTOANKICODEDISPLAY today"
141+
// maskGlobalReg example: /OBSTOANKICODEDISPLAY/g
142+
const maskGlobalRegex: RegExp = new RegExp(mask, 'g');
143+
144+
const matchCount: number = (note_text.match(maskGlobalRegex) || []).length;
145+
146+
// Validate that we have exactly enough replacements
147+
if (matchCount !== replacements.length) {
148+
throw new Error(`Mismatch between placeholders (${matchCount}) and replacements (${replacements.length})`);
149+
}
150+
151+
// replacements example: ["10", "15"]
152+
note_text = note_text.replace(maskGlobalRegex, () => {
153+
const replacement: string = replacements[index++];
141154
return escape ? escapeHtml(replacement) : replacement;
142155
});
156+
157+
// note_text expected: "The 10 is worth 15 today"
158+
return note_text;
143159
}
144160

145161
format(note_text: string, cloze: boolean, highlights_to_cloze: boolean): string {

0 commit comments

Comments
 (0)