wrapRegExp.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var _typeof = require("@babel/runtime-corejs3/helpers/typeof")["default"];
  2. var _WeakMap = require("@babel/runtime-corejs3/core-js/weak-map");
  3. var _Symbol$replace = require("@babel/runtime-corejs3/core-js/symbol/replace");
  4. var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/slice");
  5. var _reduceInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/reduce");
  6. var _Object$keys = require("@babel/runtime-corejs3/core-js/object/keys");
  7. var _Object$create = require("@babel/runtime-corejs3/core-js/object/create");
  8. var setPrototypeOf = require("./setPrototypeOf.js");
  9. var inherits = require("./inherits.js");
  10. function _wrapRegExp() {
  11. module.exports = _wrapRegExp = function _wrapRegExp(re, groups) {
  12. return new BabelRegExp(re, undefined, groups);
  13. };
  14. module.exports["default"] = module.exports, module.exports.__esModule = true;
  15. var _super = RegExp.prototype;
  16. var _groups = new _WeakMap();
  17. function BabelRegExp(re, flags, groups) {
  18. var _this = new RegExp(re, flags);
  19. _groups.set(_this, groups || _groups.get(re));
  20. return setPrototypeOf(_this, BabelRegExp.prototype);
  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 = arguments;
  38. if (_typeof(args[args.length - 1]) !== "object") {
  39. args = _sliceInstanceProperty([]).call(args);
  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 _context;
  50. var g = _groups.get(re);
  51. return _reduceInstanceProperty(_context = _Object$keys(g)).call(_context, function (groups, name) {
  52. groups[name] = result[g[name]];
  53. return groups;
  54. }, _Object$create(null));
  55. }
  56. return _wrapRegExp.apply(this, arguments);
  57. }
  58. module.exports = _wrapRegExp;
  59. module.exports["default"] = module.exports, module.exports.__esModule = true;