Skip to content

Commit

Permalink
Simplify regex-shorthand logic
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Nov 30, 2019
1 parent b99b9a9 commit adb8382
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 31 deletions.
36 changes: 9 additions & 27 deletions rules/regex-shorthand.js
@@ -1,6 +1,6 @@
'use strict';
const cleanRegexp = require('clean-regexp');
const {generate, optimize, parse} = require('regexp-tree');
const {optimize} = require('regexp-tree');
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');

Expand All @@ -9,45 +9,27 @@ const message = 'Use regex shorthands to improve readability.';
const create = context => {
return {
'Literal[regex]': node => {
const {type, value} = context.getSourceCode().getFirstToken(node);
const {raw: original} = node;

if (type !== 'RegularExpression') {
return;
}

let parsedSource;
let optimized
try {
parsedSource = parse(value);
} catch (error) {
context.report({
node,
message: '{{original}} can\'t be parsed: {{message}}',
data: {
original: value,
message: error.message
}
});

optimized = optimize(original).toString();
} catch (_) {
return;
}

const originalRegex = generate(parsedSource).toString();
const optimizedRegex = optimize(value).toString();

if (originalRegex === optimizedRegex) {
if (!optimized || original === optimized) {
return;
}

context.report({
node,
message: '{{original}} can be optimized to {{optimized}}',
data: {
original: value,
optimized: optimizedRegex
original,
optimized
},
fix(fixer) {
return fixer.replaceText(node, optimizedRegex);
}
fix: fixer => fixer.replaceText(node, optimized)
});
},
'NewExpression[callee.name="RegExp"]': node => {
Expand Down
16 changes: 12 additions & 4 deletions test/regex-shorthand.js
Expand Up @@ -20,20 +20,28 @@ ruleTester.run('regex-shorthand', rule, {
valid: [
'const foo = /\\d/',
'const foo = /\\W/i',
'const foo = /\\w/ig',
'const foo = /[a-z]/ig',
'const foo = /\\d*?/ig',
'const foo = /\\w/gi',
'const foo = /[a-z]/gi',
'const foo = /\\d*?/gi',
'const foo = new RegExp(\'\\d\')',
'const foo = new RegExp(\'\\d\', \'ig\')',
'const foo = new RegExp(\'\\d*?\')',
'const foo = new RegExp(\'[a-z]\', \'i\')',
'const foo = new RegExp(/\\d/)',
'const foo = new RegExp(/\\d/ig)',
'const foo = new RegExp(/\\d/gi)',
'const foo = new RegExp(/\\d/, \'ig\')',
'const foo = new RegExp(/\\d*?/)',
'const foo = new RegExp(/[a-z]/, \'i\')'
],
invalid: [
{
code: 'const foo = /\\w/ig',
errors: [{
...error,
message: '/\\w/ig can be optimized to /\\w/gi'
}],
output: 'const foo = /\\w/gi'
},
{
code: 'const foo = /[0-9]/',
errors: [{
Expand Down

0 comments on commit adb8382

Please sign in to comment.