wrapRegExp.js (1711B)
1 import _typeof from "./typeof.js"; 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, void 0, groups); 7 }; 8 9 var _super = RegExp.prototype, 10 _groups = new WeakMap(); 11 12 function BabelRegExp(re, flags, groups) { 13 var _this = new RegExp(re, flags); 14 15 return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); 16 } 17 18 function buildGroups(result, re) { 19 var g = _groups.get(re); 20 21 return Object.keys(g).reduce(function (groups, name) { 22 return groups[name] = result[g[name]], groups; 23 }, Object.create(null)); 24 } 25 26 return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { 27 var result = _super.exec.call(this, str); 28 29 return result && (result.groups = buildGroups(result, this)), result; 30 }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { 31 if ("string" == typeof substitution) { 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 } 38 39 if ("function" == typeof substitution) { 40 var _this = this; 41 42 return _super[Symbol.replace].call(this, str, function () { 43 var args = arguments; 44 return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); 45 }); 46 } 47 48 return _super[Symbol.replace].call(this, str, substitution); 49 }, _wrapRegExp.apply(this, arguments); 50 }