\$\begingroup\$
\$\endgroup\$
We've developed an ESLint rule to determine if a tag name used inside the Protractor's by.tagName()
locator is valid.
A Tag Name is considered valid when:
- It can contain alphanumeric characters.
- It can contain the dash(-) symbol.
- It cannot start with dash or a number.
- It cannot end with dash.
The Code:
'use strict'
var isTagName = /^[A-Za-z][A-Za-z0-9-]*$/
module.exports = {
meta: {
schema: []
},
create: function (context) {
return {
'CallExpression': function (node) {
var object = node.callee.object
var property = node.callee.property
var insideByTagName = object && property && object.name === 'by' && property.name === 'tagName'
var argumentExists = node.arguments && node.arguments.length && node.arguments[0].value
if (insideByTagName && argumentExists) {
var tagName = node.arguments[0].value
if (!tagName.match(isTagName) || tagName.endsWith('-')) {
context.report({
node: node,
message: 'Invalid TagName value: "' + tagName + '"'
})
}
}
}
}
}
}
Is it possible to decrease nested-ness and improve on readability?
FYI, using standard
JS code style.
asked Jul 11, 2017 at 19:03
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
The original code is fine IMO, but technically it's possible to flatten using a complete regexp
var isTagName = /^[A-Za-z]([A-Za-z0-9-]*[A-Za-z0-9])?$/
plus dubious/stinky value fallbacks and ES2015 arrow function:
create: context => ({
CallExpression: node => {
if ((node.callee.object || {}).name !== 'by' ||
(node.callee.property || {}).name !== 'tagName') {
return
}
var tagName = ((node.arguments || [])[0] || {}).value
if (tagName && !tagName.match(isTagName)) {
context.report({
node,
message: `Invalid tag name: "${tagName}"`
})
}
}
})
answered Jul 12, 2017 at 7:31
-
2\$\begingroup\$ You can use shorter regex
/^[a-z](-?[a-z0-9]+)*$/i
\$\endgroup\$Tushar– Tushar2017年07月12日 07:33:47 +00:00Commented Jul 12, 2017 at 7:33 -
2\$\begingroup\$ And use
RegExp#test
instead ofString#match
to check if the string contains the pattern.match
is used for data extraction. \$\endgroup\$Tushar– Tushar2017年07月12日 07:35:42 +00:00Commented Jul 12, 2017 at 7:35
default