Skip to content

Commit 3d211f5

Browse files
Merge pull request #269 from Richienb/opt-zero-one
Optimize `a{0,1}` → `a?`
2 parents 16f37ad + 66108a5 commit 3d211f5

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/optimizer/transforms/__tests__/quantifier-range-to-symbol-transform-test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,11 @@ describe('quantifier range to symbol', () => {
4545
expect(re.toString()).toBe('/[a-z]{3}/');
4646
});
4747

48+
it('a{0,1} -> a?', () => {
49+
const re = transform('/[a-z]{0,1}/', [
50+
quantifierRangeToSymbol
51+
]);
52+
expect(re.toString()).toBe('/[a-z]?/');
53+
});
54+
4855
});

src/optimizer/transforms/quantifier-range-to-symbol-transform.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* a{0,} -> a*
1313
* a{1,} -> a+
1414
* a{1} -> a
15+
* a{0,1} -> a?
1516
*
1617
* NOTE: the following is automatically handled in the generator:
1718
*
@@ -33,6 +34,9 @@ module.exports = {
3334

3435
// a{1} -> a
3536
rewriteExactOne(path);
37+
38+
// a{0,1} -> a?
39+
rewriteZeroOne(path);
3640
}
3741
};
3842

@@ -67,3 +71,14 @@ function rewriteExactOne(path) {
6771

6872
path.parentPath.replace(path.parentPath.node.expression);
6973
}
74+
75+
function rewriteZeroOne(path) {
76+
const {node} = path;
77+
78+
if (node.from !== 0 || node.to !== 1) {
79+
return;
80+
}
81+
82+
node.kind = '?';
83+
delete node.from;
84+
}

0 commit comments

Comments
 (0)