wrapRegExp.js 2.6 KB

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