Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <[email protected]>
*/

'use strict';

const {transform} = require('../../../transform');
const removeEmptyGroup = require('../remove-empty-group-transform');

describe('remove empty groups', () => {

it('removes empty groups', () => {
const re = transform(/a(?:)b/, [
removeEmptyGroup
]);
expect(re.toString()).toBe('/ab/');

const re2 = transform(/((?:))/, [
removeEmptyGroup
]);
expect(re2.toString()).toBe('/()/');
});

it('does not remove empty regexp', () => {
const re = transform(/(?:)/, [
removeEmptyGroup
]);
expect(re.toString()).toBe('/(?:)/');
});

it('removes empty group quantifier', () => {
const re = transform(/(?:)+/, [
removeEmptyGroup
]);
expect(re.toString()).toBe('/(?:)/');
});

});
3 changes: 3 additions & 0 deletions src/optimizer/transforms/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ module.exports = [
// (a|b|c) -> [abc]
require('./group-single-chars-to-char-class'),

// (?:)a -> a
require('./remove-empty-group-transform'),

// (?:a) -> a
require('./ungroup-transform')
];
34 changes: 34 additions & 0 deletions src/optimizer/transforms/remove-empty-group-transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <[email protected]>
*/

'use strict';

/**
* A regexp-tree plugin to remove non-capturing empty groups.
*
* /(?:)a/ -> /a/
* /a|(?:)/ -> /a|/
*/

module.exports = {
Group(path) {
const {node, parent} = path;
const childPath = path.getChild();

if (node.capturing || childPath) {
return;
}

if (parent.type === 'Repetition') {

path.getParent().replace(node);

} else if (parent.type !== 'RegExp') {

path.remove();

}
}
};