Skip to content

Commit

Permalink
util: support array of formats in util.styelText
Browse files Browse the repository at this point in the history
  • Loading branch information
marco-ippolito committed Mar 11, 2024
1 parent 328642b commit fcb9e0d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
5 changes: 3 additions & 2 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -1800,7 +1800,8 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
added: v21.7.0
-->
* `format` {string} A text format defined in `util.inspect.colors`.
* `format` {string | Array} A text format or an Array
of text formats defined in `util.inspect.colors`.
* `text` {string} The text to to be formatted.
This function returns a formatted text considering the `format` passed.
Expand All @@ -1822,7 +1823,7 @@ console.log(errorMessage);
```cjs
console.log(
util.styleText('underline', util.styleText('italic', 'My italic underlined message')),
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
```
Expand Down
16 changes: 16 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,22 @@ function pad(n) {
*/
function styleText(format, text) {
validateString(text, 'text');

if (ArrayIsArray(format) && format.length > 0) {
let formatCodes = '';
let append = '';
for (const f of format) {
const formatCode = inspect.colors[f];
if (formatCode == null) {
validateOneOf(f, 'format', ObjectKeys(inspect.colors));
}
formatCodes += `\u001b[${formatCode[0]}m`;
append += `\u001b[${formatCode[1]}m`;
}

return `${formatCodes}${text}${append}`;
}

const formatCodes = inspect.colors[format];
if (formatCodes == null) {
validateOneOf(format, 'format', ObjectKeys(inspect.colors));
Expand Down
8 changes: 8 additions & 0 deletions test/parallel/test-util-styletext.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,11 @@ assert.throws(() => {
});

assert.strictEqual(util.styleText('red', 'test'), '\u001b[31mtest\u001b[39m');

assert.strictEqual(util.styleText(['red', 'bold'], 'test'), '\u001b[31m\u001b[1mtest\u001b[39m\u001b[22m');

assert.throws(() => {
util.styleText(['invalid'], 'text');
}, {
code: 'ERR_INVALID_ARG_VALUE',
});

0 comments on commit fcb9e0d

Please sign in to comment.