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

Refactor to synchronous functions, update ts and vitest config #1

Merged
merged 3 commits into from
Nov 12, 2023
Merged
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
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,21 @@ import wisely from 'wisely';
const text = 'Palestine will be free! Freedom is the right of ALL nations!';

// Obscuring the whole text
await wisely({ text });
// Output: P@l3$t|n3 w!ll 83 fr33! Fr33d0m |$ t#3 r!6#t 0f @LL n4t|0n5!
const res1 = wisely({ text });

// Only obscures the specified phrases
await wisely({ text, phrases: ['palestine', 'free'] });
// Output: P4l35t1n3 will be fr33! Freedom is the right of ALL nations!
const res2 = wisely({ text, phrases: ['palestine', 'free'] });

console.log(res1, res2);
// P@l3$t|n3 w!ll 83 fr33! Fr33d0m |$ t#3 r!6#t 0f @LL n4t|0n5!
// P4l35t1n3 will be fr33! Freedom is the right of ALL nations!
```

## API

### wisely(options)

Returns a `Promise` that resolves to a `string` with the obsfucated text.
Returns a `string` with the obsfucated text.

#### options

Expand Down
18 changes: 14 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export type CharSetNames = 'latin' | 'latin-1';
export type CharSet = Record<string, string[] | undefined>;

async function getCharSet(name: CharSetNames = 'latin'): Promise<CharSet> {
return import(`../charsets/${name}.json`) as Promise<CharSet>;
const dirname = path.dirname(fileURLToPath(import.meta.url));

function getCharSet(name: CharSetNames = 'latin'): CharSet {
const strJson = fs.readFileSync(
path.resolve(dirname, `../charsets/${name}.json`),
{ encoding: 'utf8' },
);
return JSON.parse(strJson) as CharSet;
}

function getChar(char: string, charSet: CharSet, caseSensitive?: boolean) {
Expand All @@ -26,8 +36,8 @@ export type Options = {
charSet?: CharSetNames;
};

export default async function wisely(options: Options): Promise<string> {
const charSet = await getCharSet(options.charSet);
export default function wisely(options: Options): string {
const charSet = getCharSet(options.charSet);

const censor = (phrase: string): string => phrase.split('')
.map((char) => getChar(char, charSet, options.caseSensitive))
Expand Down
4 changes: 2 additions & 2 deletions test/benchmark.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { performance } from 'perf_hooks';
import fs from 'node:fs';
import wisely from '~/index.js';

test('perf on large string must <= 20ms', async () => {
test('large text', () => {
const text = fs.readFileSync('test/large-string.txt', 'utf-8');

const startTime = performance.now();
const res = await wisely({ text, phrases: ['pulau'] });
const res = wisely({ text, phrases: ['pulau'] });
const diff = performance.now() - startTime;

console.log(`Perf: ${diff}ms`);
Expand Down
28 changes: 14 additions & 14 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import wisely from '~/index.js';
describe('wisely', () => {
const text = 'Palestine will be free! Freedom is the right of ALL nations!';

test('valid', async () => {
const result = await wisely({ text });
test('valid', () => {
const result = wisely({ text });

expect(result).not.equal('');
expect(result).not.equal(text);
Expand All @@ -16,10 +16,10 @@ describe('wisely', () => {
test.each([
{ phrase: 'palestine', unaffected: 'will be' },
{ phrase: 'free', unaffected: 'Freedom' },
])('with specific phrases provided: $phrase', async ({
])('with specific phrases provided: $phrase', ({
phrase, unaffected,
}) => {
const result = await wisely({ text, phrases: [phrase] });
const result = wisely({ text, phrases: [phrase] });

expect(result).contain(unaffected);
expect(result).not.match(new RegExp(`\\b${phrase}\\b`, 'i'));
Expand All @@ -29,8 +29,8 @@ describe('wisely', () => {
test.each([
{ testText: 'AABBCCDDz', contains: '48Dz', notContains: '@BC2' },
{ testText: 'aabbccddZ', contains: '@6cd2', notContains: '48Dz' },
])('case sensitive: $testText', async ({ testText, contains, notContains }) => {
const result = await wisely({ text: testText, caseSensitive: true });
])('case sensitive: $testText', ({ testText, contains, notContains }) => {
const result = wisely({ text: testText, caseSensitive: true });

contains.split('').forEach((char) => {
expect(result).contain(char);
Expand All @@ -43,22 +43,22 @@ describe('wisely', () => {
expect(result).toHaveLength(testText.length);
});

test('no phrases found in the text', async () => {
expect(await wisely({ text, phrases: ['foo'] })).toEqual(text);
test('no phrases found in the text', () => {
expect(wisely({ text, phrases: ['foo'] })).toEqual(text);
});

test('empty text', async () => {
expect(await wisely({ text: '' })).toEqual('');
test('empty text', () => {
expect(wisely({ text: '' })).toEqual('');
});

test('empty phrases', async () => {
expect(await wisely({ text, phrases: [] })).toEqual(text);
test('empty phrases', () => {
expect(wisely({ text, phrases: [] })).toEqual(text);
});

test.each([
{ testText: 'AaBbCcDdXxZz', contains: '\u00df\u00d7Zz', notContains: 'AaBbCcDdXx' },
])('with specific charSet (latin-1): $testText', async ({ testText, contains, notContains }) => {
const result = await wisely({ text: testText, charSet: 'latin-1' });
])('with specific charSet (latin-1): $testText', ({ testText, contains, notContains }) => {
const result = wisely({ text: testText, charSet: 'latin-1' });

contains.split('').forEach((char) => {
expect(result).contain(char);
Expand Down
11 changes: 3 additions & 8 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
],
"target": "ESNext",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "lib",
"module": "Node16",
"moduleResolution": "Node16",
"esModuleInterop": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"baseUrl": "./",
Expand All @@ -20,7 +16,6 @@
],
},
"strict": true,
"resolveJsonModule": true,
},
"exclude": [
"node_modules",
Expand Down
2 changes: 1 addition & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export default defineConfig({
test: {
root: './',
alias: {
'~': path.resolve(__dirname, './src'),
'~': path.resolve('./src'),
},
coverage: {
provider: 'v8',
Expand Down