wrapRegExp.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _wrapRegExp;
  6. var _setPrototypeOf = require("setPrototypeOf");
  7. var _inherits = require("inherits");
  8. function _wrapRegExp() {
  9. exports.default = _wrapRegExp = function (re, groups) {
  10. return new BabelRegExp(re, undefined, groups);
  11. };
  12. var _super = RegExp.prototype;
  13. var _groups = new WeakMap();
  14. function BabelRegExp(re, flags, groups) {
  15. var _this = new RegExp(re, flags);
  16. _groups.set(_this, groups || _groups.get(re));
  17. return _setPrototypeOf(_this, BabelRegExp.prototype);
  18. }
  19. _inherits(BabelRegExp, RegExp);
  20. BabelRegExp.prototype.exec = function (str) {
  21. var result = _super.exec.call(this, str);
  22. if (result) {
  23. result.groups = buildGroups(result, this);
  24. var indices = result.indices;
  25. if (indices) indices.groups = buildGroups(indices, this);
  26. }
  27. return result;
  28. };
  29. BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
  30. if (typeof substitution === "string") {
  31. var groups = _groups.get(this);
  32. return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
  33. var group = groups[name];
  34. return "$" + (Array.isArray(group) ? group.join("$") : group);
  35. }));
  36. } else if (typeof substitution === "function") {
  37. var _this = this;
  38. return _super[Symbol.replace].call(this, str, function () {
  39. var args = arguments;
  40. if (typeof args[args.length - 1] !== "object") {
  41. args = [].slice.call(args);
  42. args.push(buildGroups(args, _this));
  43. }
  44. return substitution.apply(this, args);
  45. });
  46. } else {
  47. return _super[Symbol.replace].call(this, str, substitution);
  48. }
  49. };
  50. function buildGroups(result, re) {
  51. var g = _groups.get(re);
  52. return Object.keys(g).reduce(function (groups, name) {
  53. var i = g[name];
  54. if (typeof i === "number") groups[name] = result[i];else {
  55. var k = 0;
  56. while (result[i[k]] === undefined && k + 1 < i.length) k++;
  57. groups[name] = result[i[k]];
  58. }
  59. return groups;
  60. }, Object.create(null));
  61. }
  62. return _wrapRegExp.apply(this, arguments);
  63. }
  64. //# sourceMappingURL=wrapRegExp.js.map