Skip to content

Commit 00b9d4b

Browse files
authored
chore: prefer string templates over string concatenation (#732)
1 parent cb746cb commit 00b9d4b

25 files changed

+203
-226
lines changed

.eslintrc.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ module.exports = defineConfig({
2929
// We may want to use this in the future
3030
'no-useless-escape': 'off',
3131
eqeqeq: ['error', 'always', { null: 'ignore' }],
32+
'prefer-template': 'error',
3233

3334
'@typescript-eslint/ban-ts-comment': 'warn',
3435
'@typescript-eslint/consistent-type-imports': 'error',

scripts/apidoc/apiDocsWriter.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ export function writeApiDocsModulePage(
6464

6565
content = vitePressInFileOptions + formatMarkdown(content);
6666

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

7070
/**
@@ -87,7 +87,7 @@ export function writeApiDocsDirectPage(methodName: string): void {
8787

8888
content = vitePressInFileOptions + formatMarkdown(content);
8989

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

9393
/**
@@ -111,7 +111,7 @@ export const ${lowerModuleName}: Method[] = ${JSON.stringify(
111111

112112
contentTs = formatTypescript(contentTs);
113113

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

117117
/**

scripts/apidoc/signature.ts

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export function prettifyMethodName(method: string): string {
2929
export function toBlock(comment?: Comment): string {
3030
return (
3131
(comment?.shortText.trim() || 'Missing') +
32-
(comment?.text ? '\n\n' + comment.text : '')
32+
(comment?.text ? `\n\n${comment.text}` : '')
3333
);
3434
}
3535

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

122122
examples += `faker.${moduleName}.${methodName}()`;
123-
examples += (example ? ` // => ${example}` : '') + '\n';
123+
examples += `${example ? ` // => ${example}` : ''}\n`;
124124
} catch (error) {
125125
// Ignore the error => hide the example call + result.
126126
}
@@ -131,7 +131,7 @@ export function analyzeSignature(
131131
.map((tag) => tag.text.trimEnd()) || [];
132132

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

137137
const seeAlsos =
@@ -140,13 +140,15 @@ export function analyzeSignature(
140140
.map((t) => t.text.trim()) ?? [];
141141

142142
const prettyMethodName = prettifyMethodName(methodName);
143+
const code = '```';
144+
143145
return {
144146
name: methodName,
145147
title: prettyMethodName,
146148
description: mdToHtml(toBlock(signature.comment)),
147149
parameters: parameters,
148150
returns: typeToText(signature.type),
149-
examples: mdToHtml('```ts\n' + examples + '```'),
151+
examples: mdToHtml(`${code}ts\n${examples}${code}`),
150152
deprecated: signature.comment?.hasTag('deprecated') ?? false,
151153
seeAlsos,
152154
};
@@ -164,10 +166,10 @@ function analyzeParameter(parameter: ParameterReflection): {
164166

165167
let signatureText = '';
166168
if (defaultValue) {
167-
signatureText = ' = ' + defaultValue;
169+
signatureText = ` = ${defaultValue}`;
168170
}
169171

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

172174
const parameters: MethodParameter[] = [
173175
{
@@ -256,27 +258,28 @@ function declarationTypeToText(
256258
switch (declaration.kind) {
257259
case ReflectionKind.Method:
258260
return signatureTypeToText(declaration.signatures[0]);
261+
259262
case ReflectionKind.Property:
260263
return typeToText(declaration.type);
264+
261265
case ReflectionKind.TypeLiteral:
262266
if (declaration.children?.length) {
263267
if (short) {
264268
// This is too long for the parameter table, thus we abbreviate this.
265269
return '{ ... }';
266270
}
267-
return (
268-
'{' +
269-
declaration.children
270-
.map((c) => `\n${c.name}: ${declarationTypeToText(c)}`)
271-
.join()
272-
.replace(/\n/g, '\n ') +
273-
'\n}'
274-
);
271+
272+
const list = declaration.children
273+
.map((c) => ` ${c.name}: ${declarationTypeToText(c)}`)
274+
.join(',\n');
275+
276+
return `{\n${list}\n}`;
275277
} else if (declaration.signatures?.length) {
276278
return signatureTypeToText(declaration.signatures[0]);
277279
} else {
278280
return declaration.toString();
279281
}
282+
280283
default:
281284
return declaration.toString();
282285
}

scripts/generateLocales.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ function generateLocaleFile(locale: string): void {
101101
`;
102102

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

107107
function tryLoadLocalesMainIndexFile(pathModules: string): LocaleDefinition {
@@ -253,7 +253,7 @@ function updateLocaleFileHook(
253253
localePath: string[]
254254
): void {
255255
if (filePath === 'never') {
256-
console.log(filePath + ' <-> ' + locale + ' @ ' + localePath.join(' -> '));
256+
console.log(`${filePath} <-> ${locale} @ ${localePath.join(' -> ')}`);
257257
}
258258
}
259259

@@ -285,13 +285,14 @@ for (const locale of locales) {
285285
generateLocaleFile(locale);
286286

287287
// src/locales/**/index.ts
288+
const separator = localeSeparator ? `\nseparator: '${localeSeparator}',` : '';
289+
288290
generateRecursiveModuleIndexes(
289291
pathModules,
290292
locale,
291293
'LocaleDefinition',
292294
1,
293-
`title: '${localeTitle}',` +
294-
(localeSeparator ? `\nseparator: '${localeSeparator}',` : '')
295+
`title: '${localeTitle}',${separator}`
295296
);
296297
}
297298

scripts/verifyCommit.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,22 @@ const isMergeCommit = msg.startsWith('Merge remote-tracking-branch');
1818

1919
if (!isMergeCommit && !releaseRE.test(msg) && !commitRE.test(msg)) {
2020
console.log();
21+
2122
console.error(
2223
` ${colors.bgRed(colors.white(' ERROR '))} ${colors.red(
2324
`invalid commit message format.`
24-
)}\n\n` +
25-
colors.red(
26-
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
27-
) +
28-
` ${colors.green(`feat: add 'comments' option`)}\n` +
29-
` ${colors.green(`fix: handle events on blur (close #28)`)}\n\n` +
30-
colors.red(` See .github/commit-convention.md for more details.\n`)
25+
)}
26+
27+
${colors.red(
28+
`Proper commit message format is required for automated changelog generation. Examples:`
29+
)}
30+
31+
${colors.green(`feat: add 'comments' option`)}
32+
${colors.green(`fix: handle events on blur (close #28)`)}
33+
34+
${colors.red(`See .github/commit-convention.md for more details.`)}
35+
`
3136
);
37+
3238
process.exit(1);
3339
}

src/address.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ export class Address {
230230
let result: string;
231231
let suffix = this.streetSuffix();
232232
if (suffix !== '') {
233-
suffix = ' ' + suffix;
233+
suffix = ` ${suffix}`;
234234
}
235235

236236
switch (this.faker.datatype.number(1)) {
@@ -381,7 +381,7 @@ export class Address {
381381
.number({
382382
min,
383383
max,
384-
precision: parseFloat((0.0).toPrecision(precision) + '1'),
384+
precision: parseFloat(`${(0.0).toPrecision(precision)}1`),
385385
})
386386
.toFixed(precision);
387387
}
@@ -406,7 +406,7 @@ export class Address {
406406
.number({
407407
max: max,
408408
min: min,
409-
precision: parseFloat((0.0).toPrecision(precision) + '1'),
409+
precision: parseFloat(`${(0.0).toPrecision(precision)}1`),
410410
})
411411
.toFixed(precision);
412412
}

src/commerce.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,7 @@ export class Commerce {
4545
* faker.commerce.productName() // 'Incredible Soft Gloves'
4646
*/
4747
productName(): string {
48-
return (
49-
this.productAdjective() +
50-
' ' +
51-
this.productMaterial() +
52-
' ' +
53-
this.product()
54-
);
48+
return `${this.productAdjective()} ${this.productMaterial()} ${this.product()}`;
5549
}
5650

5751
/**

src/datatype.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ export class Datatype {
243243
]);
244244
}
245245

246-
return '0x' + wholeString;
246+
return `0x${wholeString}`;
247247
}
248248

249249
/**

src/fake.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@ export class Fake {
8989
const parts = method.split('.');
9090

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

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

9999
// assign the function from the module.function namespace

src/finance.ts

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export class Finance {
9696
let template = '';
9797

9898
for (let i = 0; i < length; i++) {
99-
template = template + '#';
99+
template = `${template}#`;
100100
}
101101

102102
//prefix with ellipsis
@@ -332,7 +332,7 @@ export class Finance {
332332
: this.faker.random.arrayElement(iban.formats);
333333

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

338338
let s = '';
@@ -387,20 +387,21 @@ export class Finance {
387387
bic(): string {
388388
const vowels = ['A', 'E', 'I', 'O', 'U'];
389389
const prob = this.faker.datatype.number(100);
390-
return (
391-
this.faker.helpers.replaceSymbols('???') +
392-
this.faker.random.arrayElement(vowels) +
393-
this.faker.random.arrayElement(iban.iso3166) +
394-
this.faker.helpers.replaceSymbols('?') +
395-
'1' +
396-
(prob < 10
390+
391+
return [
392+
this.faker.helpers.replaceSymbols('???'),
393+
this.faker.random.arrayElement(vowels),
394+
this.faker.random.arrayElement(iban.iso3166),
395+
this.faker.helpers.replaceSymbols('?'),
396+
'1',
397+
prob < 10
397398
? this.faker.helpers.replaceSymbols(
398-
'?' + this.faker.random.arrayElement(vowels) + '?'
399+
`?${this.faker.random.arrayElement(vowels)}?`
399400
)
400401
: prob < 40
401402
? this.faker.helpers.replaceSymbols('###')
402-
: '')
403-
);
403+
: '',
404+
].join('');
404405
}
405406

406407
/**
@@ -418,18 +419,7 @@ export class Finance {
418419
const company = transaction.business;
419420
const card = this.mask();
420421
const currency = this.currencyCode();
421-
return (
422-
transactionType +
423-
' transaction at ' +
424-
company +
425-
' using card ending with ***' +
426-
card +
427-
' for ' +
428-
currency +
429-
' ' +
430-
amount +
431-
' in account ***' +
432-
account
433-
);
422+
423+
return `${transactionType} transaction at ${company} using card ending with ***${card} for ${currency} ${amount} in account ***${account}`;
434424
}
435425
}

src/git.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ export class Git {
4242
branch(): string {
4343
const noun = this.faker.hacker.noun().replace(' ', '-');
4444
const verb = this.faker.hacker.verb().replace(' ', '-');
45-
return noun + '-' + verb;
45+
return `${noun}-${verb}`;
4646
}
4747

4848
/**

src/helpers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ export class Helpers {
481481
return '';
482482
}
483483
for (const p in data) {
484-
const re = new RegExp('{{' + p + '}}', 'g');
484+
const re = new RegExp(`{{${p}}}`, 'g');
485485
const value = data[p];
486486
if (typeof value === 'string') {
487487
str = str.replace(re, value);

src/image.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ export class Image {
104104
}
105105
let url = `${protocol}loremflickr.com/${width}/${height}`;
106106
if (category != null) {
107-
url += '/' + category;
107+
url += `/${category}`;
108108
}
109109

110110
if (randomize) {

src/image_providers/lorempicsum.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ export class LoremPicsum {
104104
let url = 'https://picsum.photos';
105105

106106
if (seed) {
107-
url += '/seed/' + seed;
107+
url += `/seed/${seed}`;
108108
}
109109

110110
url += `/${width}/${height}`;
@@ -114,7 +114,7 @@ export class LoremPicsum {
114114
}
115115

116116
if (grayscale) {
117-
return url + '?grayscale';
117+
return `${url}?grayscale`;
118118
}
119119

120120
if (blur) {

src/image_providers/lorempixel.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export class Lorempixel {
6767

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

7373
if (randomize) {

0 commit comments

Comments
 (0)