Skip to content

Commit 192228b

Browse files
authoredApr 25, 2022
refactor(cli): apply optimizations (#574)
• List the available types by a `ListFormat` formatter. • Replace unnecessary conditional check. • Use switch statement for better readablity and performance. • Avoid casting strings to strings.
1 parent 19ddfb6 commit 192228b

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed
 

‎lib/cli.js

+19-14
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ const QUESTION_TYPE = {
1919
CONFIRM: 'confirm'
2020
};
2121

22+
const formatter = new Intl.ListFormat('en', { type: 'disjunction' });
23+
2224
function head(text, length = 11) {
2325
return chalk.bold(text.padEnd(length));
2426
}
@@ -54,12 +56,11 @@ export default class CLI {
5456
const availableTypes = Object.values(QUESTION_TYPE);
5557
if (!availableTypes.includes(questionType)) {
5658
throw new Error(
57-
`${questionType} must be one of ${availableTypes.join(', ')}`);
59+
`${questionType} must be one of ${formatter.format(availableTypes)}`);
5860
}
5961

60-
const defaultAnswer = (opts.defaultAnswer === undefined)
61-
? true
62-
: opts.defaultAnswer;
62+
const defaultAnswer = (opts.defaultAnswer === undefined) ||
63+
opts.defaultAnswer;
6364
if (typeof defaultAnswer === 'boolean' &&
6465
questionType !== QUESTION_TYPE.CONFIRM) {
6566
throw new Error(
@@ -95,14 +96,18 @@ export default class CLI {
9596

9697
stopSpinner(rawText, status = SUCCESS) {
9798
let symbol;
98-
if (status === SUCCESS) {
99-
symbol = success;
100-
} else if (status === FAILED) {
101-
symbol = error;
102-
} else if (status === WARN) {
103-
symbol = warning;
104-
} else if (status === INFO) {
105-
symbol = info;
99+
switch (status) {
100+
case SUCCESS:
101+
symbol = success;
102+
break;
103+
case FAILED:
104+
symbol = error;
105+
break;
106+
case WARN:
107+
symbol = warning;
108+
break;
109+
case INFO:
110+
symbol = info;
106111
}
107112
const text = ' ' + rawText;
108113
this.spinner.stopAndPersist({
@@ -155,9 +160,9 @@ export default class CLI {
155160
const prefix = options.newline ? this.eolIndent : this.figureIndent;
156161
if (obj instanceof Error) {
157162
this.log(`${prefix}${error} ${obj.message}`);
158-
this.log(`${obj.stack}`);
163+
this.log(obj.stack);
159164
if (obj.data) {
160-
this.log(`${JSON.stringify(obj.data, null, 2)}`);
165+
this.log(JSON.stringify(obj.data, null, 2));
161166
}
162167
} else {
163168
this.log(prefix + chalk.bold(`${error} ${obj}`));

0 commit comments

Comments
 (0)
Please sign in to comment.