| 1 |
|
| 2 |
|
| 3 |
import setPrototypeOf from "setPrototypeOf"; |
| 4 |
import inherits from "inherits"; |
| 5 |
|
| 6 |
export default function _wrapRegExp() { |
| 7 |
_wrapRegExp = function (re, groups) { |
| 8 |
return new BabelRegExp(re, undefined, groups); |
| 9 |
}; |
| 10 |
|
| 11 |
var _super = RegExp.prototype; |
| 12 |
var _groups = new WeakMap(); |
| 13 |
|
| 14 |
function BabelRegExp(re, flags, groups) { |
| 15 |
var _this = new RegExp(re, flags); |
| 16 |
|
| 17 |
_groups.set(_this, groups || _groups.get(re)); |
| 18 |
return setPrototypeOf(_this, BabelRegExp.prototype); |
| 19 |
} |
| 20 |
inherits(BabelRegExp, RegExp); |
| 21 |
|
| 22 |
BabelRegExp.prototype.exec = function (str) { |
| 23 |
var result = _super.exec.call(this, str); |
| 24 |
if (result) { |
| 25 |
result.groups = buildGroups(result, this); |
| 26 |
var indices = result.indices; |
| 27 |
if (indices) indices.groups = buildGroups(indices, this); |
| 28 |
} |
| 29 |
return result; |
| 30 |
}; |
| 31 |
BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { |
| 32 |
if (typeof substitution === "string") { |
| 33 |
var groups = _groups.get(this); |
| 34 |
return _super[Symbol.replace].call( |
| 35 |
this, |
| 36 |
str, |
| 37 |
substitution.replace(/\$<([^>]+)>/g, function (_, name) { |
| 38 |
var group = groups[name]; |
| 39 |
return "$" + (Array.isArray(group) ? group.join("$") : group); |
| 40 |
}) |
| 41 |
); |
| 42 |
} else if (typeof substitution === "function") { |
| 43 |
var _this = this; |
| 44 |
return _super[Symbol.replace].call(this, str, function () { |
| 45 |
var args = arguments; |
| 46 |
|
| 47 |
if (typeof args[args.length - 1] !== "object") { |
| 48 |
args = [].slice.call(args); |
| 49 |
args.push(buildGroups(args, _this)); |
| 50 |
} |
| 51 |
return substitution.apply(this, args); |
| 52 |
}); |
| 53 |
} else { |
| 54 |
return _super[Symbol.replace].call(this, str, substitution); |
| 55 |
} |
| 56 |
}; |
| 57 |
|
| 58 |
function buildGroups(result, re) { |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
var g = _groups.get(re); |
| 63 |
return Object.keys(g).reduce(function (groups, name) { |
| 64 |
var i = g[name]; |
| 65 |
if (typeof i === "number") groups[name] = result[i]; |
| 66 |
else { |
| 67 |
|
| 68 |
var k = 0; |
| 69 |
|
| 70 |
|
| 71 |
while (result[i[k]] === undefined && k + 1 < i.length) k++; |
| 72 |
groups[name] = result[i[k]]; |
| 73 |
} |
| 74 |
return groups; |
| 75 |
}, Object.create(null)); |
| 76 |
} |
| 77 |
|
| 78 |
return _wrapRegExp.apply(this, arguments); |
| 79 |
} |