wrapRegExp.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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, void 0, groups);
  7. }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  8. var _super = RegExp.prototype,
  9. _groups = new WeakMap();
  10. function BabelRegExp(re, flags, groups) {
  11. var _this = new RegExp(re, flags);
  12. return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype);
  13. }
  14. function buildGroups(result, re) {
  15. var g = _groups.get(re);
  16. return Object.keys(g).reduce(function (groups, name) {
  17. return groups[name] = result[g[name]], groups;
  18. }, Object.create(null));
  19. }
  20. return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {
  21. var result = _super.exec.call(this, str);
  22. return result && (result.groups = buildGroups(result, this)), result;
  23. }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
  24. if ("string" == typeof substitution) {
  25. var groups = _groups.get(this);
  26. return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  27. return "$" + groups[name];
  28. }));
  29. }
  30. if ("function" == typeof substitution) {
  31. var _this = this;
  32. return _super[Symbol.replace].call(this, str, function () {
  33. var args = arguments;
  34. return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);
  35. });
  36. }
  37. return _super[Symbol.replace].call(this, str, substitution);
  38. }, _wrapRegExp.apply(this, arguments);
  39. }
  40. module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports;