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.

\$\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}"`
        })
      }
    }
  })
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can use shorter regex /^[a-z](-?[a-z0-9]+)*$/i \$\endgroup\$
    – Tushar
    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\$
    – Tushar
    Commented Jul 12, 2017 at 7:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.