index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const utils = require('eslint-plugin-vue/lib/utils')
  2. module.exports = Object.assign(
  3. {
  4. getProperty (node, name, condition) {
  5. return node.properties.find(
  6. p => p.type === 'Property' && name === utils.getStaticPropertyName(p) && condition(p)
  7. )
  8. },
  9. getProperties (node, names) {
  10. return node.properties.filter(
  11. p => p.type === 'Property' && (!names.size || names.has(utils.getStaticPropertyName(p)))
  12. )
  13. },
  14. getFunctionWithName (rootNode, name) {
  15. return this.getProperty(
  16. rootNode,
  17. name,
  18. item => item.value.type === 'ArrowFunctionExpression' || item.value.type === 'FunctionExpression'
  19. )
  20. },
  21. isInFunction (func, child) {
  22. if (func.value.type === 'FunctionExpression') {
  23. if (
  24. child &&
  25. child.loc.start.line >= func.value.loc.start.line &&
  26. child.loc.end.line <= func.value.loc.end.line
  27. ) {
  28. return true
  29. }
  30. }
  31. },
  32. * getFunctionWithChild (rootNode, funcNames, childNodes) {
  33. const funcNodes = this.getProperties(rootNode, funcNames)
  34. for (const func of funcNodes) {
  35. for (const { name, node: child } of childNodes) {
  36. const funcName = utils.getStaticPropertyName(func)
  37. if (!funcName) continue
  38. if (this.isInFunction(func, child)) {
  39. yield { name, node: child, func, funcName }
  40. }
  41. }
  42. }
  43. },
  44. isOpenParen (token) {
  45. return token.type === 'Punctuator' && token.value === '('
  46. },
  47. isCloseParen (token) {
  48. return token.type === 'Punctuator' && token.value === ')'
  49. },
  50. getFirstAndLastTokens (node, sourceCode) {
  51. let first = sourceCode.getFirstToken(node)
  52. let last = sourceCode.getLastToken(node)
  53. // If the value enclosed by parentheses, update the 'first' and 'last' by the parentheses.
  54. while (true) {
  55. const prev = sourceCode.getTokenBefore(first)
  56. const next = sourceCode.getTokenAfter(last)
  57. if (this.isOpenParen(prev) && this.isCloseParen(next)) {
  58. first = prev
  59. last = next
  60. } else {
  61. return { first, last }
  62. }
  63. }
  64. }
  65. },
  66. utils
  67. )