wrapRegExp.js 2.3 KB

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