1 | import _typeof from "@babel/runtime/helpers/typeof";
|
2 | import setPrototypeOf from "./setPrototypeOf.js";
|
3 | import inherits from "./inherits.js";
|
4 | export default function _wrapRegExp() {
|
5 | _wrapRegExp = function _wrapRegExp(re, groups) {
|
6 | return new BabelRegExp(re, undefined, groups);
|
7 | };
|
8 |
|
9 | var _super = RegExp.prototype;
|
10 |
|
11 | var _groups = new WeakMap();
|
12 |
|
13 | function BabelRegExp(re, flags, groups) {
|
14 | var _this = new RegExp(re, flags);
|
15 |
|
16 | _groups.set(_this, groups || _groups.get(re));
|
17 |
|
18 | return setPrototypeOf(_this, BabelRegExp.prototype);
|
19 | }
|
20 |
|
21 | inherits(BabelRegExp, RegExp);
|
22 |
|
23 | BabelRegExp.prototype.exec = function (str) {
|
24 | var result = _super.exec.call(this, str);
|
25 |
|
26 | if (result) result.groups = buildGroups(result, this);
|
27 | return result;
|
28 | };
|
29 |
|
30 | BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
|
31 | if (typeof substitution === "string") {
|
32 | var groups = _groups.get(this);
|
33 |
|
34 | return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
|
35 | return "$" + groups[name];
|
36 | }));
|
37 | } else if (typeof substitution === "function") {
|
38 | var _this = this;
|
39 |
|
40 | return _super[Symbol.replace].call(this, str, function () {
|
41 | var args = arguments;
|
42 |
|
43 | if (_typeof(args[args.length - 1]) !== "object") {
|
44 | args = [].slice.call(args);
|
45 | args.push(buildGroups(args, _this));
|
46 | }
|
47 |
|
48 | return substitution.apply(this, args);
|
49 | });
|
50 | } else {
|
51 | return _super[Symbol.replace].call(this, str, substitution);
|
52 | }
|
53 | };
|
54 |
|
55 | function buildGroups(result, re) {
|
56 | var g = _groups.get(re);
|
57 |
|
58 | return Object.keys(g).reduce(function (groups, name) {
|
59 | groups[name] = result[g[name]];
|
60 | return groups;
|
61 | }, Object.create(null));
|
62 | }
|
63 |
|
64 | return _wrapRegExp.apply(this, arguments);
|
65 | } |
\ | No newline at end of file |