1
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can use shorter regex /^[a-z](-?[a-z0-9]+)*$/i \$\endgroup\$ Commented Jul 12, 2017 at 7:33
  • 2
    \$\begingroup\$ And use RegExp#test instead of String#match to check if the string contains the pattern. match is used for data extraction. \$\endgroup\$ Commented Jul 12, 2017 at 7:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.