-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
101 lines (88 loc) · 2.09 KB
/
index.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <[email protected]>
*/
'use strict';
/**
* The `RegExpTree` class provides runtime support for `compat-transpiler`
* module from `regexp-tree`.
*
* E.g. it tracks names of the capturing groups, in order to access the
* names on the matched result.
*
* It's a thin-wrapper on top of original regexp.
*/
class RegExpTree {
/**
* Initializes a `RegExpTree` instance.
*
* @param RegExp - a regular expression
*
* @param Object state:
*
* An extra state which may store any related to transformation
* data, for example, names of the groups.
*
* - flags - original flags
* - groups - names of the groups, and their indices
* - source - original source
*/
constructor(re, {
flags,
groups,
source,
}) {
this._re = re;
this._groups = groups;
// Original props.
this.flags = flags;
this.source = source || re.source;
this.dotAll = flags.includes('s');
// Inherited directly from `re`.
this.global = re.global;
this.ignoreCase = re.ignoreCase;
this.multiline = re.multiline;
this.sticky = re.sticky;
this.unicode = re.unicode;
this.hasIndices = re.hasIndices;
}
/**
* Facade wrapper for RegExp `test` method.
*/
test(string) {
return this._re.test(string);
}
/**
* Facade wrapper for RegExp `compile` method.
*/
compile(string) {
return this._re.compile(string);
}
/**
* Facade wrapper for RegExp `toString` method.
*/
toString() {
if (!this._toStringResult) {
this._toStringResult = `/${this.source}/${this.flags}`;
}
return this._toStringResult;
}
/**
* Facade wrapper for RegExp `exec` method.
*/
exec(string) {
const result = this._re.exec(string);
if (!this._groups || !result) {
return result;
}
result.groups = {};
for (const group in this._groups) {
const groupNumber = this._groups[group];
result.groups[group] = result[groupNumber];
}
return result;
}
}
module.exports = {
RegExpTree,
};