wrapRegExp.js (1923B)
1 var _typeof = require("./typeof.js")["default"]; 2 3 var setPrototypeOf = require("./setPrototypeOf.js"); 4 5 var inherits = require("./inherits.js"); 6 7 function _wrapRegExp() { 8 module.exports = _wrapRegExp = function _wrapRegExp(re, groups) { 9 return new BabelRegExp(re, void 0, groups); 10 }, module.exports.__esModule = true, module.exports["default"] = module.exports; 11 12 var _super = RegExp.prototype, 13 _groups = new WeakMap(); 14 15 function BabelRegExp(re, flags, groups) { 16 var _this = new RegExp(re, flags); 17 18 return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); 19 } 20 21 function buildGroups(result, re) { 22 var g = _groups.get(re); 23 24 return Object.keys(g).reduce(function (groups, name) { 25 return groups[name] = result[g[name]], groups; 26 }, Object.create(null)); 27 } 28 29 return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { 30 var result = _super.exec.call(this, str); 31 32 return result && (result.groups = buildGroups(result, this)), result; 33 }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { 34 if ("string" == typeof substitution) { 35 var groups = _groups.get(this); 36 37 return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { 38 return "$" + groups[name]; 39 })); 40 } 41 42 if ("function" == typeof substitution) { 43 var _this = this; 44 45 return _super[Symbol.replace].call(this, str, function () { 46 var args = arguments; 47 return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); 48 }); 49 } 50 51 return _super[Symbol.replace].call(this, str, substitution); 52 }, _wrapRegExp.apply(this, arguments); 53 } 54 55 module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports;