Skip to content

Commit 1542aa5

Browse files
perf(util): optimise styleText
1 parent 93892d7 commit 1542aa5

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

lib/util.js

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ function styleText(format, text, { validateStream = true, stream = process.stdou
119119
validateString(text, 'text');
120120
validateBoolean(validateStream, 'options.validateStream');
121121

122+
let shouldColorize = true;
122123
if (validateStream) {
123124
if (
124125
!isReadableStream(stream) &&
@@ -128,28 +129,30 @@ function styleText(format, text, { validateStream = true, stream = process.stdou
128129
throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream);
129130
}
130131

131-
if (!lazyUtilColors().shouldColorize(stream)) {
132-
return text;
133-
};
132+
// If the stream is falsy or should not be colorized, set skipColorize to true
133+
shouldColorize = lazyUtilColors().shouldColorize(stream);
134134
}
135135

136136
// If the format is not an array, convert it to an array
137137
const formatArray = ArrayIsArray(format) ? format : [format];
138+
const { colors } = inspect;
138139

139-
let left = '';
140-
let right = '';
141-
for (const key of formatArray) {
142-
const formatCodes = inspect.colors[key];
140+
// We want to loop through the format array to check if the format is valid
141+
// including if it's shouldn't be colorized
142+
const { left, right } = formatArray.reduce((acc, key) => {
143+
const formatCodes = colors[key];
143144
// If the format is not a valid style, throw an error
144145
if (formatCodes == null) {
145-
validateOneOf(key, 'format', ObjectKeys(inspect.colors));
146+
validateOneOf(key, 'format', ObjectKeys(colors));
146147
}
148+
if(shouldColorize) {
149+
acc.left += escapeStyleCode(formatCodes[0]);
150+
acc.right = `${escapeStyleCode(formatCodes[1])}${acc.right}`;
151+
}
152+
return acc;
153+
}, { left: '', right: '' });
147154

148-
left += escapeStyleCode(formatCodes[0]);
149-
right = `${escapeStyleCode(formatCodes[1])}${right}`;
150-
}
151-
152-
return `${left}${text}${right}`;
155+
return shouldColorize ? `${left}${text}${right}` : text;
153156
}
154157

155158
/**

0 commit comments

Comments
 (0)