1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
*/
'use strict';
/**
* A regexp-tree plugin to replace single char character classes with
* just that character.
*
* [\d] -> \d, [^\w] -> \W
*/
module.exports = {
CharacterClass: function CharacterClass(path) {
var node = path.node;
if (node.expressions.length !== 1 || !isAppropriateChar(node.expressions[0])) {
return;
}
var _node$expressions$ = node.expressions[0],
value = _node$expressions$.value,
kind = _node$expressions$.kind,
escaped = _node$expressions$.escaped;
if (node.negative) {
// For negative can extract only meta chars like [^\w] -> \W
// cannot do for [^a] -> a (wrong).
if (!isMeta(value)) {
return;
}
value = getInverseMeta(value);
}
path.replace({
type: 'Char',
value: value,
kind: kind,
escaped: escaped || shouldEscape(value)
});
}
};
function isAppropriateChar(node) {
return node.type === 'Char' &&
// We don't extract [\b] (backspace) since \b has different
// semantics (word boundary).
node.value !== '\\b';
}
function isMeta(value) {
return (/^\\[dwsDWS]$/.test(value)
);
}
function getInverseMeta(value) {
return (/[dws]/.test(value) ? value.toUpperCase() : value.toLowerCase()
);
}
// Note: \{ and \} are always preserved to avoid `a[{]2[}]` turning
// into `a{2}`.
function shouldEscape(value) {
return (/[*[()+?$./{}|]/.test(value)
);
}