resolveObjectPatternPropertyToValue.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import getPropertyValuePath from './getPropertyValuePath.js';
  2. import resolveToValue from './resolveToValue.js';
  3. function resolveToObjectExpression(path) {
  4. if (path.isVariableDeclarator()) {
  5. const init = path.get('init');
  6. if (init.hasNode()) {
  7. return resolveToValue(init);
  8. }
  9. }
  10. else if (path.isAssignmentExpression()) {
  11. if (path.node.operator === '=') {
  12. return resolveToValue(path.get('right'));
  13. }
  14. }
  15. return null;
  16. }
  17. /**
  18. * Resolve and ObjectProperty inside an ObjectPattern to its value if possible
  19. * If not found `null` is returned
  20. */
  21. export default function resolveObjectPatternPropertyToValue(path) {
  22. if (!path.parentPath.isObjectPattern()) {
  23. return null;
  24. }
  25. const resolved = resolveToObjectExpression(path.parentPath.parentPath);
  26. if (resolved && resolved.isObjectExpression()) {
  27. const propertyPath = getPropertyValuePath(resolved,
  28. // Always id in ObjectPattern
  29. path.get('key').node.name);
  30. if (propertyPath) {
  31. return resolveToValue(propertyPath);
  32. }
  33. }
  34. return null;
  35. }