Created
November 30, 2018 08:02
-
-
Save conorhastings/8adae8e063a6ee8acf1684d3ed724a1a to your computer and use it in GitHub Desktop.
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
export default function(babel) { | |
const { types: t } = babel; | |
return { | |
visitor: { | |
VariableDeclaration(path) { | |
const node = path.node; | |
if (node.declarations && node.declarations.length === 1) { | |
const [{ init }] = node.declarations; | |
if (t.isTemplateLiteral(init)) { | |
if ( | |
init.expressions && | |
init.expressions.length === 1 && | |
t.isObjectExpression(init.expressions[0]) && | |
init.quasis && | |
init.quasis.length === 2 && | |
init.quasis[1].value.raw.includes(":") | |
) { | |
const [, pickObject] = init.quasis[1].value.raw.split(":"); | |
if (path.scope.hasBinding(pickObject)) { | |
const restructuredProperties = init.expressions[0].properties; | |
const nodeToPickFrom = | |
path.scope.bindings[pickObject].path.node.init; | |
const nodeToPickFromIsObject = t.isObjectExpression(nodeToPickFrom); | |
const propertiesToPick = init.expressions[0].properties.map( | |
prop => prop.value.name | |
); | |
path.replaceWith( | |
t.variableDeclaration(node.kind, [ | |
t.variableDeclarator( | |
t.identifier(node.declarations[0].id.name), | |
t.objectExpression( | |
propertiesToPick.map( | |
prop => ( | |
t.identifier(node.declarations[0].id.name), | |
t.objectProperty( | |
t.identifier(prop), | |
t.memberExpression( | |
t.identifier(pickObject), | |
t.identifier(prop) | |
) | |
) | |
) | |
) | |
) | |
) | |
]) | |
); | |
} | |
} | |
} | |
} | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment