You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.9 KiB

4 years ago
  1. import _typeof from "../../helpers/esm/typeof";
  2. import wrapNativeSuper from "./wrapNativeSuper";
  3. import getPrototypeOf from "./getPrototypeOf";
  4. import possibleConstructorReturn from "./possibleConstructorReturn";
  5. import inherits from "./inherits";
  6. export default function _wrapRegExp(re, groups) {
  7. _wrapRegExp = function _wrapRegExp(re, groups) {
  8. return new BabelRegExp(re, undefined, groups);
  9. };
  10. var _RegExp = wrapNativeSuper(RegExp);
  11. var _super = RegExp.prototype;
  12. var _groups = new WeakMap();
  13. function BabelRegExp(re, flags, groups) {
  14. var _this = _RegExp.call(this, re, flags);
  15. _groups.set(_this, groups || _groups.get(re));
  16. return _this;
  17. }
  18. inherits(BabelRegExp, _RegExp);
  19. BabelRegExp.prototype.exec = function (str) {
  20. var result = _super.exec.call(this, str);
  21. if (result) result.groups = buildGroups(result, this);
  22. return result;
  23. };
  24. BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
  25. if (typeof substitution === "string") {
  26. var groups = _groups.get(this);
  27. return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  28. return "$" + groups[name];
  29. }));
  30. } else if (typeof substitution === "function") {
  31. var _this = this;
  32. return _super[Symbol.replace].call(this, str, function () {
  33. var args = [];
  34. args.push.apply(args, arguments);
  35. if (_typeof(args[args.length - 1]) !== "object") {
  36. args.push(buildGroups(args, _this));
  37. }
  38. return substitution.apply(this, args);
  39. });
  40. } else {
  41. return _super[Symbol.replace].call(this, str, substitution);
  42. }
  43. };
  44. function buildGroups(result, re) {
  45. var g = _groups.get(re);
  46. return Object.keys(g).reduce(function (groups, name) {
  47. groups[name] = result[g[name]];
  48. return groups;
  49. }, Object.create(null));
  50. }
  51. return _wrapRegExp.apply(this, arguments);
  52. }