Skip to content

Commit

Permalink
feat: implement util.styleText (#9287)
Browse files Browse the repository at this point in the history
* feat: implement util.styleText

* i forgot to test
  • Loading branch information
paperdave committed Mar 7, 2024
1 parent 9734f4c commit e8374eb
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/js/node/util.js
Expand Up @@ -240,6 +240,23 @@ var toUSVString = input => {
return (input + "").toWellFormed();
};

function styleText(format, text) {
if (typeof text !== "string") {
const e = new Error(`The text argument must be of type string. Received type ${typeof text}`);
e.code = "ERR_INVALID_ARG_TYPE";
throw e;
}
const formatCodes = inspect.colors[format];
if (formatCodes == null) {
const e = new Error(
`The value "${typeof format === "symbol" ? format.description : format}" is invalid for argument 'format'. Reason: must be one of: ${Object.keys(inspect.colors).join(", ")}`,
);
e.code = "ERR_INVALID_ARG_VALUE";
throw e;
}
return `\u001b[${formatCodes[0]}m${text}\u001b[${formatCodes[1]}m`;
}

export default Object.assign(cjs_exports, {
format,
formatWithOptions,
Expand Down Expand Up @@ -273,4 +290,5 @@ export default Object.assign(cjs_exports, {
TextDecoder,
TextEncoder,
parseArgs,
styleText,
});
32 changes: 32 additions & 0 deletions test/js/node/util/util.test.js
Expand Up @@ -325,4 +325,36 @@ describe("util", () => {
"wow({ obj: \u001B[33mtrue\u001B[39m })",
);
});

it("styleText", () => {
[undefined, null, false, 5n, 5, Symbol(), () => {}, {}, []].forEach(invalidOption => {
assert.throws(
() => {
util.styleText(invalidOption, "test");
},
{
code: "ERR_INVALID_ARG_VALUE",
},
);
assert.throws(
() => {
util.styleText("red", invalidOption);
},
{
code: "ERR_INVALID_ARG_TYPE",
},
);
});

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

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

0 comments on commit e8374eb

Please sign in to comment.