Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a blacklist for randomCharFromSetCensorStrategy #84

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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('@$$');
}
});
});