diff --git a/javascriptv3/example_code/libs/tests/util-string.unit.test.js b/javascriptv3/example_code/libs/tests/util-string.unit.test.js index 3a297a7f8d9..8c25520abb2 100644 --- a/javascriptv3/example_code/libs/tests/util-string.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-string.unit.test.js @@ -17,10 +17,10 @@ describe("util-string", () => { expect(u1).not.toEqual(u2); }); - it("should return undefined if a falsy value is passed in", () => { - expect(getUniqueName()).toBeUndefined(); - expect(getUniqueName("")).toBeUndefined(); - expect(getUniqueName(0)).toBeUndefined(); + it("should throw an error if a falsy value is passed in for the prefix", () => { + expect(() => getUniqueName()).toThrowError(); + expect(() => getUniqueName("")).toThrowError(); + expect(() => getUniqueName(0)).toThrowError(); }); }); diff --git a/javascriptv3/example_code/libs/utils/util-node.js b/javascriptv3/example_code/libs/utils/util-node.js index 563fe17be89..1d7dac9cff3 100644 --- a/javascriptv3/example_code/libs/utils/util-node.js +++ b/javascriptv3/example_code/libs/utils/util-node.js @@ -12,3 +12,32 @@ export const setEnv = (/** @type {string} */ key, value) => { * @param {string | URL} fileUrl */ export const isMain = (fileUrl) => process.argv[1] === fileURLToPath(fileUrl); + +/** + * @typedef {import("node:util").ParseArgsConfig} ParseArgsConfig + * @typedef {ReturnType} ParsedResults + * + * @param {import("node:util").ParseArgsConfig} config + * @param {ParsedResults} results + * @returns {{ errors: string[] | null }} + */ +export const validateArgs = (config, results) => { + if (!config.options) { + return {}; + } + + /** @type {string[] | null} */ + let errors = null; + + for (const option in config.options) { + const optionRequired = config.options[option]?.required; + const optionPresent = Object.hasOwn(results.values, option); + + if (optionRequired && !optionPresent) { + errors = errors ?? []; + errors.push(`Missing required argument "${option}".`); + } + + return { errors }; + } +}; diff --git a/javascriptv3/example_code/libs/utils/util-string.js b/javascriptv3/example_code/libs/utils/util-string.js index fc65146fa05..9bda0a14211 100644 --- a/javascriptv3/example_code/libs/utils/util-string.js +++ b/javascriptv3/example_code/libs/utils/util-string.js @@ -3,14 +3,18 @@ import { v4 as uuidv4 } from "uuid"; /** - * @param {string} name + * @param {string} prefix */ -export const getUniqueName = (name) => { - if (!name) { - return; +export const getUniqueName = (prefix) => { + class GetUniqueNameError extends Error { + name = GetUniqueNameError.name; } - return `${name.toLowerCase()}-${uuidv4()}`; + if (!prefix) { + throw new GetUniqueNameError("Prefix is missing."); + } + + return `${prefix.toLowerCase()}-${uuidv4()}`; }; /**