wrapRegExp.js 2.1 KB

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