|
| 1 | +'use strict'; |
| 2 | +const getDocsUrl = require('./utils/get-docs-url'); |
| 3 | + |
| 4 | +const getMethodName = callee => { |
| 5 | + const {property} = callee; |
| 6 | + |
| 7 | + if (property.type === 'Identifier') { |
| 8 | + return property.name; |
| 9 | + } |
| 10 | + |
| 11 | + return null; |
| 12 | +}; |
| 13 | + |
| 14 | +const getCallerName = callee => { |
| 15 | + const {object} = callee; |
| 16 | + |
| 17 | + if (object.type === 'Identifier') { |
| 18 | + return object.name; |
| 19 | + } |
| 20 | + |
| 21 | + if (object.type === 'MemberExpression') { |
| 22 | + const {property} = object; |
| 23 | + |
| 24 | + if (property.type === 'Identifier') { |
| 25 | + return property.name; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return null; |
| 30 | +}; |
| 31 | + |
| 32 | +const getArgumentName = args => { |
| 33 | + const [identifier] = args; |
| 34 | + |
| 35 | + if (identifier.type === 'ThisExpression') { |
| 36 | + return 'this'; |
| 37 | + } |
| 38 | + |
| 39 | + if (identifier.type === 'Identifier') { |
| 40 | + return identifier.name; |
| 41 | + } |
| 42 | + |
| 43 | + return null; |
| 44 | +}; |
| 45 | + |
| 46 | +const create = context => { |
| 47 | + return { |
| 48 | + CallExpression(node) { |
| 49 | + const {callee} = node; |
| 50 | + |
| 51 | + if (node.arguments.length === 0 || |
| 52 | + callee.type !== 'MemberExpression' || |
| 53 | + callee.computed |
| 54 | + ) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + const methodName = getMethodName(callee); |
| 59 | + const callerName = getCallerName(callee); |
| 60 | + |
| 61 | + if (methodName === 'removeChild' && ( |
| 62 | + callerName === 'parentNode' || |
| 63 | + callerName === 'parentElement' |
| 64 | + )) { |
| 65 | + const argumentName = getArgumentName(node.arguments); |
| 66 | + |
| 67 | + if (argumentName) { |
| 68 | + context.report({ |
| 69 | + node, |
| 70 | + message: `Prefer \`remove\` over \`${callerName}.removeChild\``, |
| 71 | + fix: fixer => fixer.replaceText(node, `${argumentName}.remove()`) |
| 72 | + }); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + }; |
| 77 | +}; |
| 78 | + |
| 79 | +module.exports = { |
| 80 | + create, |
| 81 | + meta: { |
| 82 | + docs: { |
| 83 | + url: getDocsUrl(__filename) |
| 84 | + }, |
| 85 | + fixable: 'code' |
| 86 | + } |
| 87 | +}; |
0 commit comments