Skip to content

Instantly share code, notes, and snippets.

@christianbundy
Last active Mar 24, 2020
Embed
What would you like to do?
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