Skip to content

Instantly share code, notes, and snippets.

@christianbundy
Last active March 24, 2020 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianbundy/4c3c29b9f1a52384d7e8a51a956227c2 to your computer and use it in GitHub Desktop.
Save christianbundy/4c3c29b9f1a52384d7e8a51a956227c2 to your computer and use it in GitHub Desktop.
required arguments without explicit names
const required = (argumentName = false) => {
try {
const fs = require("fs");
// Get the stack trace.
const copy = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const stack = new Error().stack;
Error.prepareStackTrace = copy;
const fileName = stack[1].getFileName();
const lineNumber = stack[1].getLineNumber() - 1;
const columnNumber = stack[1].getColumnNumber() - 1;
const line = fs.readFileSync(fileName, "utf8").split("\n")[lineNumber];
const partialLine = line.slice(0, columnNumber);
const groups = partialLine.match("(\\S+)\\s?=\\s?$");
argumentName = groups[groups.length - 1];
} catch (e) {
// No Node.js, no problem. :)
}
const error = new Error(
`Missing argument${argumentName ? ` (${argumentName})` : ""}.`
);
Error.captureStackTrace(error, required);
throw error;
};
function foo({ puppy = required() } = {}) {
console.log(puppy);
}
// Output: Error: Missing argument (puppy).
foo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment