wrapRegExp.js 2.0 KB

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