Skip to content

Instantly share code, notes, and snippets.

@insin
Last active December 22, 2015 09:21
Show Gist options
  • Save insin/9a939300ea44d42d6b4c to your computer and use it in GitHub Desktop.
Save insin/9a939300ea44d42d6b4c to your computer and use it in GitHub Desktop.
A Babel 6 transform which finds default argument mandatory() calls and inserts argument index and name

A Babel 6 transform which finds mandatory() calls which are the default expression for named function parameters and inserts parameter index and name information.

Based on this discussion on Twitter

Try it out in AST Explorer by selecting Transform → babelv6 from the top menu.

Sample code:

function mandatory(argPosition, name) {
  throw new Error(`argument at ${argPosition} called ${name} is mandatory`)
}

function foo(mustBeProvided = mandatory()) {
  return mustBeProvided
}
export default function ({types: t}) {
return {
visitor: {
FunctionDeclaration(path) {
path.node.params.forEach((param, index) => {
if (t.isIdentifier(param.left) &&
t.isAssignmentPattern(param) &&
t.isCallExpression(param.right) &&
param.right.callee.name === 'mandatory' &&
param.right.arguments.length === 0) {
param.right.arguments[0] = t.numberLiteral(index)
param.right.arguments[1] = t.stringLiteral(param.left.name)
}
})
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment