implementation.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var Call = require('es-abstract/2020/Call');
  3. var Get = require('es-abstract/2020/Get');
  4. var GetMethod = require('es-abstract/2020/GetMethod');
  5. var IsRegExp = require('es-abstract/2020/IsRegExp');
  6. var ToString = require('es-abstract/2020/ToString');
  7. var RequireObjectCoercible = require('es-abstract/2020/RequireObjectCoercible');
  8. var callBound = require('call-bind/callBound');
  9. var hasSymbols = require('has-symbols')();
  10. var flagsGetter = require('regexp.prototype.flags');
  11. var $indexOf = callBound('String.prototype.indexOf');
  12. var regexpMatchAllPolyfill = require('./polyfill-regexp-matchall');
  13. var getMatcher = function getMatcher(regexp) { // eslint-disable-line consistent-return
  14. var matcherPolyfill = regexpMatchAllPolyfill();
  15. if (hasSymbols && typeof Symbol.matchAll === 'symbol') {
  16. var matcher = GetMethod(regexp, Symbol.matchAll);
  17. if (matcher === RegExp.prototype[Symbol.matchAll] && matcher !== matcherPolyfill) {
  18. return matcherPolyfill;
  19. }
  20. return matcher;
  21. }
  22. // fallback for pre-Symbol.matchAll environments
  23. if (IsRegExp(regexp)) {
  24. return matcherPolyfill;
  25. }
  26. };
  27. module.exports = function matchAll(regexp) {
  28. var O = RequireObjectCoercible(this);
  29. if (typeof regexp !== 'undefined' && regexp !== null) {
  30. var isRegExp = IsRegExp(regexp);
  31. if (isRegExp) {
  32. // workaround for older engines that lack RegExp.prototype.flags
  33. var flags = 'flags' in regexp ? Get(regexp, 'flags') : flagsGetter(regexp);
  34. RequireObjectCoercible(flags);
  35. if ($indexOf(ToString(flags), 'g') < 0) {
  36. throw new TypeError('matchAll requires a global regular expression');
  37. }
  38. }
  39. var matcher = getMatcher(regexp);
  40. if (typeof matcher !== 'undefined') {
  41. return Call(matcher, regexp, [O]);
  42. }
  43. }
  44. var S = ToString(O);
  45. // var rx = RegExpCreate(regexp, 'g');
  46. var rx = new RegExp(regexp, 'g');
  47. return Call(getMatcher(rx), rx, [S]);
  48. };