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

chore: prefer string templates over string concatenation #732

Merged
merged 24 commits into from
Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from 17 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
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ module.exports = defineConfig({
// We may want to use this in the future
'no-useless-escape': 'off',
eqeqeq: ['error', 'always', { null: 'ignore' }],
'prefer-template': 'error',

'@typescript-eslint/ban-ts-comment': 'warn',
'@typescript-eslint/consistent-type-imports': 'error',
Expand Down
6 changes: 3 additions & 3 deletions scripts/apidoc/apiDocsWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function writeApiDocsModulePage(

content = vitePressInFileOptions + format(content, prettierMarkdown);

writeFileSync(resolve(pathOutputDir, lowerModuleName + '.md'), content);
writeFileSync(resolve(pathOutputDir, `${lowerModuleName}.md`), content);
}

/**
Expand All @@ -100,7 +100,7 @@ export function writeApiDocsDirectPage(methodName: string): void {

content = vitePressInFileOptions + format(content, prettierMarkdown);

writeFileSync(resolve(pathOutputDir, methodName + '.md'), content);
writeFileSync(resolve(pathOutputDir, `${methodName}.md`), content);
}

/**
Expand All @@ -124,7 +124,7 @@ export const ${lowerModuleName}: Method[] = ${JSON.stringify(

contentTs = format(contentTs, prettierTypescript);

writeFileSync(resolve(pathOutputDir, lowerModuleName + '.ts'), contentTs);
writeFileSync(resolve(pathOutputDir, `${lowerModuleName}.ts`), contentTs);
}

/**
Expand Down
33 changes: 18 additions & 15 deletions scripts/apidoc/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function prettifyMethodName(method: string): string {
export function toBlock(comment?: Comment): string {
return (
(comment?.shortText.trim() || 'Missing') +
(comment?.text ? '\n\n' + comment.text : '')
(comment?.text ? `\n\n${comment.text}` : '')
);
}

Expand Down Expand Up @@ -119,11 +119,11 @@ export function analyzeSignature(
try {
let example = JSON.stringify(faker[moduleName][methodName]());
if (example.length > 50) {
example = example.substring(0, 47) + '...';
example = `${example.substring(0, 47)}...`;
}

examples += `faker.${moduleName}.${methodName}()`;
examples += (example ? ` // => ${example}` : '') + '\n';
examples += `${example ? ` // => ${example}` : ''}\n`;
} catch (error) {
// Ignore the error => hide the example call + result.
}
Expand All @@ -134,7 +134,7 @@ export function analyzeSignature(
.map((tag) => tag.text.trimEnd()) || [];

if (exampleTags.length > 0) {
examples += exampleTags.join('\n').trim() + '\n';
examples += `${exampleTags.join('\n').trim()}\n`;
}

const seeAlsos =
Expand All @@ -143,13 +143,15 @@ export function analyzeSignature(
.map((t) => t.text.trim()) ?? [];

const prettyMethodName = prettifyMethodName(methodName);
const code = '```';

return {
name: methodName,
title: prettyMethodName,
description: mdToHtml(toBlock(signature.comment)),
parameters: parameters,
returns: typeToText(signature.type),
examples: mdToHtml('```ts\n' + examples + '```'),
examples: mdToHtml(`${code}ts\n${examples}${code}`),
deprecated: signature.comment?.hasTag('deprecated') ?? false,
seeAlsos,
};
Expand All @@ -167,10 +169,10 @@ function analyzeParameter(parameter: ParameterReflection): {

let signatureText = '';
if (defaultValue) {
signatureText = ' = ' + defaultValue;
signatureText = ` = ${defaultValue}`;
}

const signature = declarationName + ': ' + typeToText(type) + signatureText;
const signature = `${declarationName}: ${typeToText(type)}${signatureText}`;

const parameters: MethodParameter[] = [
{
Expand Down Expand Up @@ -252,27 +254,28 @@ function declarationTypeToText(
switch (declaration.kind) {
case ReflectionKind.Method:
return signatureTypeToText(declaration.signatures[0]);

case ReflectionKind.Property:
return typeToText(declaration.type);

case ReflectionKind.TypeLiteral:
if (declaration.children?.length) {
if (short) {
// This is too long for the parameter table, thus we abbreviate this.
return '{ ... }';
}
return (
'{' +
declaration.children
.map((c) => `\n${c.name}: ${declarationTypeToText(c)}`)
.join()
.replace(/\n/g, '\n ') +
'\n}'
);

const list = declaration.children
.map((c) => ` ${c.name}: ${declarationTypeToText(c)}`)
.join(',\n');

return `{\n${list}\n}`;
} else if (declaration.signatures?.length) {
return signatureTypeToText(declaration.signatures[0]);
} else {
return declaration.toString();
}

default:
return declaration.toString();
}
Expand Down
9 changes: 5 additions & 4 deletions scripts/generateLocales.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function generateLocaleFile(locale: string): void {
`;

content = format(content, prettierTsOptions);
writeFileSync(resolve(pathLocale, locale + '.ts'), content);
writeFileSync(resolve(pathLocale, `${locale}.ts`), content);
}

function tryLoadLocalesMainIndexFile(pathModules: string): LocaleDefinition {
Expand Down Expand Up @@ -253,7 +253,7 @@ function updateLocaleFileHook(
localePath: string[]
): void {
if (filePath === 'never') {
console.log(filePath + ' <-> ' + locale + ' @ ' + localePath.join(' -> '));
console.log(`${filePath} <-> ${locale} @ ${localePath.join(' -> ')}`);
}
}

Expand Down Expand Up @@ -285,13 +285,14 @@ for (const locale of locales) {
generateLocaleFile(locale);

// src/locales/**/index.ts
const separator = localeSeparator ? `\nseparator: '${localeSeparator}',` : '';

generateRecursiveModuleIndexes(
pathModules,
locale,
'LocaleDefinition',
1,
`title: '${localeTitle}',` +
(localeSeparator ? `\nseparator: '${localeSeparator}',` : '')
`title: '${localeTitle}',${separator}`
);
}

Expand Down
20 changes: 13 additions & 7 deletions scripts/verifyCommit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,22 @@ const isMergeCommit = msg.startsWith('Merge remote-tracking-branch');

if (!isMergeCommit && !releaseRE.test(msg) && !commitRE.test(msg)) {
console.log();

console.error(
` ${colors.bgRed(colors.white(' ERROR '))} ${colors.red(
`invalid commit message format.`
)}\n\n` +
colors.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${colors.green(`feat: add 'comments' option`)}\n` +
` ${colors.green(`fix: handle events on blur (close #28)`)}\n\n` +
colors.red(` See .github/commit-convention.md for more details.\n`)
)}

${colors.red(
`Proper commit message format is required for automated changelog generation. Examples:`
)}

${colors.green(`feat: add 'comments' option`)}
${colors.green(`fix: handle events on blur (close #28)`)}

${colors.red(`See .github/commit-convention.md for more details.`)}
`
);

process.exit(1);
}
6 changes: 3 additions & 3 deletions src/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ export class Address {
let result: string;
let suffix = this.faker.address.streetSuffix();
if (suffix !== '') {
suffix = ' ' + suffix;
suffix = ` ${suffix}`;
}

switch (this.faker.datatype.number(1)) {
Expand Down Expand Up @@ -381,7 +381,7 @@ export class Address {
.number({
min,
max,
precision: parseFloat((0.0).toPrecision(precision) + '1'),
precision: parseFloat(`${(0.0).toPrecision(precision)}1`),
})
.toFixed(precision);
}
Expand All @@ -406,7 +406,7 @@ export class Address {
.number({
max: max,
min: min,
precision: parseFloat((0.0).toPrecision(precision) + '1'),
precision: parseFloat(`${(0.0).toPrecision(precision)}1`),
})
.toFixed(precision);
}
Expand Down
8 changes: 1 addition & 7 deletions src/commerce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,7 @@ export class Commerce {
* faker.commerce.productName() // 'Incredible Soft Gloves'
*/
productName(): string {
return (
this.faker.commerce.productAdjective() +
' ' +
this.faker.commerce.productMaterial() +
' ' +
this.faker.commerce.product()
);
return `${this.faker.commerce.productAdjective()} ${this.faker.commerce.productMaterial()} ${this.faker.commerce.product()}`;
pkuczynski marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/datatype.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ export class Datatype {
]);
}

return '0x' + wholeString;
return `0x${wholeString}`;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/fake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@ export class Fake {
const parts = method.split('.');

if (this.faker[parts[0]] == null) {
throw new FakerError('Invalid module: ' + parts[0]);
throw new FakerError(`Invalid module: ${parts[0]}`);
}

if (this.faker[parts[0]][parts[1]] == null) {
throw new FakerError('Invalid method: ' + parts[0] + '.' + parts[1]);
throw new FakerError(`Invalid method: ${parts[0]}.${parts[1]}`);
}

// assign the function from the module.function namespace
Expand Down
39 changes: 14 additions & 25 deletions src/finance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class Finance {
let template = '';

for (let i = 0; i < length; i++) {
template = template + '#';
template = `${template}#`;
}

//prefix with ellipsis
Expand Down Expand Up @@ -330,7 +330,7 @@ export class Finance {
}

if (!ibanFormat) {
throw new FakerError('Country code ' + countryCode + ' not supported.');
throw new FakerError(`Country code ${countryCode} not supported.`);
}

let s = '';
Expand Down Expand Up @@ -385,20 +385,21 @@ export class Finance {
bic(): string {
const vowels = ['A', 'E', 'I', 'O', 'U'];
const prob = this.faker.datatype.number(100);
return (
this.Helpers.replaceSymbols('???') +
this.faker.random.arrayElement(vowels) +
this.faker.random.arrayElement(this.ibanLib.iso3166) +
this.Helpers.replaceSymbols('?') +
'1' +
(prob < 10

return [
this.Helpers.replaceSymbols('???'),
this.faker.random.arrayElement(vowels),
this.faker.random.arrayElement(this.ibanLib.iso3166),
this.Helpers.replaceSymbols('?'),
'1',
prob < 10
? this.Helpers.replaceSymbols(
'?' + this.faker.random.arrayElement(vowels) + '?'
`?${this.faker.random.arrayElement(vowels)}?`
)
: prob < 40
? this.Helpers.replaceSymbols('###')
: '')
);
: '',
].join('');
}

/**
Expand All @@ -416,18 +417,6 @@ export class Finance {
const company = transaction.business;
const card = this.faker.finance.mask();
const currency = this.faker.finance.currencyCode();
return (
transactionType +
' transaction at ' +
company +
' using card ending with ***' +
card +
' for ' +
currency +
' ' +
amount +
' in account ***' +
account
);
return `${transactionType} transaction at ${company} using card ending with ***${card} for ${currency} ${amount} in account ***${account}`;
}
}
2 changes: 1 addition & 1 deletion src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class Git {
branch(): string {
const noun = this.faker.hacker.noun().replace(' ', '-');
const verb = this.faker.hacker.verb().replace(' ', '-');
return noun + '-' + verb;
return `${noun}-${verb}`;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ export class Helpers {
return '';
}
for (const p in data) {
const re = new RegExp('{{' + p + '}}', 'g');
const re = new RegExp(`{{${p}}}`, 'g');
const value = data[p];
if (typeof value === 'string') {
str = str.replace(re, value);
Expand Down
2 changes: 1 addition & 1 deletion src/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class Image {
}
let url = `${protocol}loremflickr.com/${width}/${height}`;
if (category != null) {
url += '/' + category;
url += `/${category}`;
}

if (randomize) {
Expand Down
4 changes: 2 additions & 2 deletions src/image_providers/lorempicsum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class LoremPicsum {
let url = 'https://picsum.photos';

if (seed) {
url += '/seed/' + seed;
url += `/seed/${seed}`;
}

url += `/${width}/${height}`;
Expand All @@ -114,7 +114,7 @@ export class LoremPicsum {
}

if (grayscale) {
return url + '?grayscale';
return `${url}?grayscale`;
}

if (blur) {
Expand Down
2 changes: 1 addition & 1 deletion src/image_providers/lorempixel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class Lorempixel {

let url = `https://lorempixel.com/${width}/${height}`;
if (category != null) {
url += '/' + category;
url += `/${category}`;
}

if (randomize) {
Expand Down
Loading