wrapRegExp.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import _typeof from "./typeof.js";
  2. import _WeakMap from "@babel/runtime-corejs3/core-js/weak-map";
  3. import _reduceInstanceProperty from "@babel/runtime-corejs3/core-js/instance/reduce";
  4. import _Object$keys from "@babel/runtime-corejs3/core-js/object/keys";
  5. import _Object$create from "@babel/runtime-corejs3/core-js/object/create";
  6. import _Symbol$replace from "@babel/runtime-corejs3/core-js/symbol/replace";
  7. import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js/instance/slice";
  8. import setPrototypeOf from "./setPrototypeOf.js";
  9. import inherits from "./inherits.js";
  10. export default function _wrapRegExp() {
  11. _wrapRegExp = function _wrapRegExp(re, groups) {
  12. return new BabelRegExp(re, void 0, groups);
  13. };
  14. var _super = RegExp.prototype,
  15. _groups = new _WeakMap();
  16. function BabelRegExp(re, flags, groups) {
  17. var _this = new RegExp(re, flags);
  18. return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype);
  19. }
  20. function buildGroups(result, re) {
  21. var _context;
  22. var g = _groups.get(re);
  23. return _reduceInstanceProperty(_context = _Object$keys(g)).call(_context, function (groups, name) {
  24. return groups[name] = result[g[name]], groups;
  25. }, _Object$create(null));
  26. }
  27. return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {
  28. var result = _super.exec.call(this, str);
  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. return _super[_Symbol$replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  34. return "$" + groups[name];
  35. }));
  36. }
  37. if ("function" == typeof substitution) {
  38. var _this = this;
  39. return _super[_Symbol$replace].call(this, str, function () {
  40. var args = arguments;
  41. return "object" != _typeof(args[args.length - 1]) && (args = _sliceInstanceProperty([]).call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);
  42. });
  43. }
  44. return _super[_Symbol$replace].call(this, str, substitution);
  45. }, _wrapRegExp.apply(this, arguments);
  46. }