Skip to content

Commit

Permalink
Add a blacklist for randomCharFromSetCensorStrategy
Browse files Browse the repository at this point in the history
Fixes jo3-l#82
  • Loading branch information
eltoder committed Nov 28, 2024
1 parent 6059905 commit e7979d3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/censor/BuiltinStrategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function asteriskCensorStrategy() {
* @returns A [[TextCensorStrategy]] for use with the [[TextCensor]].
*/
export function grawlixCensorStrategy() {
return randomCharFromSetCensorStrategy('%@$&*');
return randomCharFromSetCensorStrategy('%@$&*', ['@$$']);
}

/**
Expand Down Expand Up @@ -152,12 +152,15 @@ export function fixedCharCensorStrategy(char: string): TextCensorStrategy {
* be constructed. Must not be empty.
* @returns A [[TextCensorStrategy]] for use with the [[TextCensor]].
*/
export function randomCharFromSetCensorStrategy(charset: string): TextCensorStrategy {
export function randomCharFromSetCensorStrategy(charset: string, blacklist?: string[]): TextCensorStrategy {
const chars = [...charset];
if (chars.length === 0) throw new Error('The character set passed must not be empty.');
return (ctx: CensorContext) => {
let censored = '';
for (let i = 0; i < ctx.matchLength; i++) censored += chars[Math.floor(Math.random() * chars.length)];
return censored;
for (;;) {
let censored = '';
for (let i = 0; i < ctx.matchLength; i++) censored += chars[Math.floor(Math.random() * chars.length)];
if (blacklist !== undefined && blacklist.includes(censored)) continue;
return censored;
}
};
}
7 changes: 7 additions & 0 deletions test/censor/BuiltinStrategies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,11 @@ describe('randomCharFromSetCensorStrategy()', () => {
const strategy = randomCharFromSetCensorStrategy(charset);
expect([...strategy({ ...partialCtx, matchLength: 5 })].every((c) => charset.includes(c))).toBeTruthy();
});

it('should respect blacklist', () => {
const strategy = randomCharFromSetCensorStrategy('@$', ['@$$']);
for (let i = 0; i < 100; i++) {
expect(strategy({ ...partialCtx, matchLength: 3 })).not.toBe('@$$');
}
});
});

0 comments on commit e7979d3

Please sign in to comment.