wrapRegExp.js 1.8 KB

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