Last active
March 24, 2020 20:10
-
-
Save christianbundy/4c3c29b9f1a52384d7e8a51a956227c2 to your computer and use it in GitHub Desktop.
required arguments without explicit names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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