wrapRegExp.js 2.4 KB

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