is-node-matches.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. /**
  3. Check if node matches object name or key path.
  4. @param {Node} node - The AST node to check.
  5. @param {string} nameOrPath - The object name or key path.
  6. @returns {boolean}
  7. */
  8. function isNodeMatchesNameOrPath(node, nameOrPath) {
  9. const names = nameOrPath.trim().split('.');
  10. for (let index = names.length - 1; index >= 0; index--) {
  11. const name = names[index];
  12. if (!name) {
  13. return false;
  14. }
  15. if (index === 0) {
  16. return (
  17. (node.type === 'Identifier' && node.name === name)
  18. || (name === 'this' && node.type === 'ThisExpression')
  19. );
  20. }
  21. if (
  22. node.type !== 'MemberExpression'
  23. || node.optional
  24. || node.computed
  25. || node.property.type !== 'Identifier'
  26. || node.property.name !== name
  27. ) {
  28. return false;
  29. }
  30. node = node.object;
  31. }
  32. }
  33. /**
  34. Check if node matches any object name or key path.
  35. @param {Node} node - The AST node to check.
  36. @param {string[]} nameOrPaths - The object name or key paths.
  37. @returns {boolean}
  38. */
  39. function isNodeMatches(node, nameOrPaths) {
  40. return nameOrPaths.some(nameOrPath => isNodeMatchesNameOrPath(node, nameOrPath));
  41. }
  42. module.exports = {
  43. isNodeMatchesNameOrPath,
  44. isNodeMatches,
  45. };