wrapRegExp.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import _typeof from "@babel/runtime/helpers/typeof";
  2. import setPrototypeOf from "./setPrototypeOf.js";
  3. import inherits from "./inherits.js";
  4. export default function _wrapRegExp() {
  5. _wrapRegExp = function _wrapRegExp(re, groups) {
  6. return new BabelRegExp(re, void 0, groups);
  7. };
  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. }