Skip to content

Commit

Permalink
infra(unicorn): prefer-string-replace-all (#2653)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinigami92 authored Feb 18, 2024
1 parent ec5609b commit 52b8992
Show file tree
Hide file tree
Showing 19 changed files with 45 additions and 37 deletions.
2 changes: 0 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ module.exports = defineConfig({

// TODO @Shinigami92 2023-09-23: prefer-at should be turned on when we drop support for Node 14.
'unicorn/prefer-at': 'off',
// TODO @Shinigami92 2023-09-23: prefer-string-replace-all should be turned on when we drop support for Node 14.
'unicorn/prefer-string-replace-all': 'off',
// TODO @ST-DDT 2023-10-28: The following rule should be turned on when we switch to esm.
'unicorn/prefer-top-level-await': 'off',

Expand Down
7 changes: 7 additions & 0 deletions docs/guide/upgrading_v9/2653.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Examples of code-upgrades that are now used

_This upgrade is an extension to_ [#2121](./2121.md)

Used Node >= v15 feature [`replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll).

We could hint users to use polyfill or transpile-down steps.
14 changes: 7 additions & 7 deletions scripts/apidoc/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ const htmlSanitizeOptions: sanitizeHtml.IOptions = {

function comparableSanitizedHtml(html: string): string {
return html
.replace(/&#x[0-9A-F]{2};/g, (x) =>
.replaceAll(/&#x[0-9A-F]{2};/g, (x) =>
String.fromCodePoint(Number.parseInt(x.slice(3, -1), 16))
)
.replace(/>/g, '>')
.replace(/&lt;/g, '<')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/=""/g, '')
.replace(/ /g, '');
.replaceAll('&gt;', '>')
.replaceAll('&lt;', '<')
.replaceAll('&amp;', '&')
.replaceAll('&quot;', '"')
.replaceAll('=""', '')
.replaceAll(' ', '');
}

/**
Expand Down
4 changes: 2 additions & 2 deletions scripts/apidoc/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const pathOutputDir = resolve(pathDocsDir, 'api');
// Functions

export function adjustUrls(description: string): string {
return description.replace(/https:\/\/(next.)?fakerjs.dev\//g, '/');
return description.replaceAll(/https:\/\/(next.)?fakerjs.dev\//g, '/');
}

export function mapByName<TInput extends { name: string }, TValue>(
Expand All @@ -65,7 +65,7 @@ export function mapByName<TInput extends { name: string }, TValue>(
export function methodDiffHash(method: Method): string {
return diffHash({
...method,
sourcePath: method.sourcePath.replace(/#.*/g, ''),
sourcePath: method.sourcePath.replaceAll(/#.*/g, ''),
});
}

Expand Down
2 changes: 1 addition & 1 deletion scripts/apidoc/writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ async function writeApiDocsModulePage(
`
)
.join('')}
`.replace(/\n +/g, '\n');
`.replaceAll(/\n +/g, '\n');

content = vitePressInFileOptions + (await formatMarkdown(content));

Expand Down
2 changes: 1 addition & 1 deletion scripts/generate-locales.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ async function main(): Promise<void> {
localizationLocales = await formatMarkdown(localizationLocales);

let localizationContent = readFileSync(pathDocsGuideLocalization, 'utf8');
localizationContent = localizationContent.replace(
localizationContent = localizationContent.replaceAll(
/(^<!-- LOCALES-AUTO-GENERATED-START -->$).*(^<!-- LOCALES-AUTO-GENERATED-END -->$)/gms,
`$1\n\n<!-- Run '${scriptCommand}' to update. -->\n\n${localizationLocales}\n$2`
);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/color/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ function toBinary(values: number[]): string {
const buffer = new ArrayBuffer(4);
new DataView(buffer).setFloat32(0, value);
const bytes = new Uint8Array(buffer);
return toBinary([...bytes]).replace(/ /g, '');
return toBinary([...bytes]).replaceAll(' ', '');
}

return (value >>> 0).toString(2).padStart(8, '0');
Expand Down
2 changes: 1 addition & 1 deletion src/modules/finance/iban.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1407,7 +1407,7 @@ const iban: Iban = {
pattern10: ['01', '02', '03', '04', '05', '06', '07', '08', '09'],
pattern100: ['001', '002', '003', '004', '005', '006', '007', '008', '009'],
toDigitString: (str) =>
str.replace(/[A-Z]/gi, (match) =>
str.replaceAll(/[A-Z]/gi, (match) =>
String((match.toUpperCase().codePointAt(0) ?? Number.NaN) - 55)
),
};
Expand Down
2 changes: 1 addition & 1 deletion src/modules/finance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ export class FinanceModule extends ModuleBase {
format = this.faker.helpers.arrayElement(formats);
}

format = format.replace(/\//g, '');
format = format.replaceAll('/', '');
return this.faker.helpers.replaceCreditCardSymbols(format);
}

Expand Down
2 changes: 1 addition & 1 deletion src/modules/git/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export class GitModule extends ModuleBase {
const email = this.faker.internet.email({ firstName, lastName });

// Normalize user according to https://github.com/libgit2/libgit2/issues/5342
user = user.replace(/^[.,:;"\\']|[<>\n]|[.,:;"\\']$/g, '');
user = user.replaceAll(/^[.,:;"\\']|[<>\n]|[.,:;"\\']$/g, '');

lines.push(
`Author: ${user} <${email}>`,
Expand Down
8 changes: 4 additions & 4 deletions src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,9 @@ export class SimpleHelpersModule extends SimpleModuleBase {
slugify(string: string = ''): string {
return string
.normalize('NFKD') //for example è decomposes to as e + ̀
.replace(/[\u0300-\u036F]/g, '') // removes combining marks
.replace(/ /g, '-') // replaces spaces with hyphens
.replace(/[^\w.-]+/g, ''); // removes all non-word characters except for dots and hyphens
.replaceAll(/[\u0300-\u036F]/g, '') // removes combining marks
.replaceAll(' ', '-') // replaces spaces with hyphens
.replaceAll(/[^\w.-]+/g, ''); // removes all non-word characters except for dots and hyphens
}

/**
Expand Down Expand Up @@ -797,7 +797,7 @@ export class SimpleHelpersModule extends SimpleModuleBase {
let value = data[p];
if (typeof value === 'string') {
// escape $, source: https://stackoverflow.com/a/6969486/6897682
value = value.replace(/\$/g, '$$$$');
value = value.replaceAll('$', '$$$$');
str = str.replace(re, value);
} else {
str = str.replace(re, value);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/helpers/luhn-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function luhnCheckValue(str: string): number {
* @param str The string to generate the checksum for.
*/
function luhnChecksum(str: string): number {
str = str.replace(/[\s-]/g, '');
str = str.replaceAll(/[\s-]/g, '');
let sum = 0;
let alternate = false;
for (let i = str.length - 1; i >= 0; i--) {
Expand Down
14 changes: 7 additions & 7 deletions src/modules/internet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export class InternetModule extends ModuleBase {
let localPart: string = this.userName({ firstName, lastName });
// Strip any special characters from the local part of the email address
// This could happen if invalid chars are passed in manually in the firstName/lastName
localPart = localPart.replace(/[^A-Za-z0-9._+-]+/g, '');
localPart = localPart.replaceAll(/[^A-Za-z0-9._+-]+/g, '');

// The local part of an email address is limited to 64 chars per RFC 3696
// We limit to 50 chars to be more realistic
Expand All @@ -291,7 +291,7 @@ export class InternetModule extends ModuleBase {
}

// local parts may not contain two or more consecutive . characters
localPart = localPart.replace(/\.{2,}/g, '.');
localPart = localPart.replaceAll(/\.{2,}/g, '.');

// local parts may not start with or end with a . character
localPart = localPart.replace(/^\./, '');
Expand Down Expand Up @@ -661,7 +661,7 @@ export class InternetModule extends ModuleBase {
// First remove simple accents etc
result = result
.normalize('NFKD') //for example è decomposes to as e + ̀
.replace(/[\u0300-\u036F]/g, ''); // removes combining marks
.replaceAll(/[\u0300-\u036F]/g, ''); // removes combining marks

result = [...result]
.map((char) => {
Expand All @@ -681,8 +681,8 @@ export class InternetModule extends ModuleBase {
return charCode.toString(36);
})
.join('');
result = result.toString().replace(/'/g, '');
result = result.replace(/ /g, '');
result = result.toString().replaceAll("'", '');
result = result.replaceAll(' ', '');

return result;
}
Expand Down Expand Up @@ -844,8 +844,8 @@ export class InternetModule extends ModuleBase {
break;
}

result = result.toString().replace(/'/g, '');
result = result.replace(/ /g, '');
result = result.toString().replaceAll("'", '');
result = result.replaceAll(' ', '');
return result;
}

Expand Down
4 changes: 2 additions & 2 deletions src/modules/location/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export class LocationModule extends ModuleBase {
buildingNumber(): string {
return this.faker.helpers
.arrayElement(this.faker.definitions.location.building_number)
.replace(/#+/g, (m) =>
.replaceAll(/#+/g, (m) =>
this.faker.string.numeric({
length: m.length,
allowLeadingZeros: false,
Expand Down Expand Up @@ -274,7 +274,7 @@ export class LocationModule extends ModuleBase {
secondaryAddress(): string {
return this.faker.helpers
.arrayElement(this.faker.definitions.location.secondary_address)
.replace(/#+/g, (m) =>
.replaceAll(/#+/g, (m) =>
this.faker.string.numeric({
length: m.length,
allowLeadingZeros: false,
Expand Down
4 changes: 2 additions & 2 deletions src/modules/string/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -692,8 +692,8 @@ export class StringModule extends SimpleModuleBase {
*/
uuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/x/g, () => this.faker.number.hex({ min: 0x0, max: 0xf }))
.replace(/y/g, () => this.faker.number.hex({ min: 0x8, max: 0xb }));
.replaceAll('x', () => this.faker.number.hex({ min: 0x0, max: 0xf }))
.replaceAll('y', () => this.faker.number.hex({ min: 0x8, max: 0xb }));
}

/**
Expand Down
5 changes: 4 additions & 1 deletion src/modules/system/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ export class SystemModule extends ModuleBase {
): string {
const { extensionCount = 1 } = options;

const baseName = this.faker.word.words().toLowerCase().replace(/\W/g, '_');
const baseName = this.faker.word
.words()
.toLowerCase()
.replaceAll(/\W/g, '_');

const extensionsStr = this.faker.helpers
.multiple(() => this.fileExt(), { count: extensionCount })
Expand Down
2 changes: 1 addition & 1 deletion test/modules/finance.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ describe('finance', () => {
describe('creditCardNumber()', () => {
it('should return a random credit card number', () => {
let number = faker.finance.creditCardNumber();
number = number.replace(/\D/g, ''); // remove formatting
number = number.replaceAll(/\D/g, ''); // remove formatting

expect(number.length).toBeGreaterThanOrEqual(13);
expect(number.length).toBeLessThanOrEqual(20);
Expand Down
2 changes: 1 addition & 1 deletion test/modules/system.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ describe('system', () => {
const regex =
/^([0-9]|[1-5]\d|\*) ([0-9]|1\d|2[0-3]|\*) ([1-9]|[12]\d|3[01]|\*|\?) ([1-9]|1[0-2]|\*) ([0-6]|\*|\?|[A-Z]{3}) ((19[7-9]d)|20\d{2}|\*)?/;

const regexElements = regex.toString().replace(/\//g, '').split(' ');
const regexElements = regex.toString().replaceAll('/', '').split(' ');

it.each([
[{}, 5],
Expand Down
2 changes: 1 addition & 1 deletion test/scripts/apidoc/verify-jsdoc-tags.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ describe('verify JSDoc tags', () => {
).parameters) {
const { name, description } = param;
const plainDescription = description
.replace(/<[^>]+>/g, '')
.replaceAll(/<[^>]+>/g, '')
.trim();
expect(
plainDescription,
Expand Down

0 comments on commit 52b8992

Please sign in to comment.