index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var callBound = require('call-bind/callBound');
  3. var hasToStringTag = require('has-tostringtag/shams')();
  4. var has;
  5. var $exec;
  6. var isRegexMarker;
  7. var badStringifier;
  8. if (hasToStringTag) {
  9. has = callBound('Object.prototype.hasOwnProperty');
  10. $exec = callBound('RegExp.prototype.exec');
  11. isRegexMarker = {};
  12. var throwRegexMarker = function () {
  13. throw isRegexMarker;
  14. };
  15. badStringifier = {
  16. toString: throwRegexMarker,
  17. valueOf: throwRegexMarker
  18. };
  19. if (typeof Symbol.toPrimitive === 'symbol') {
  20. badStringifier[Symbol.toPrimitive] = throwRegexMarker;
  21. }
  22. }
  23. var $toString = callBound('Object.prototype.toString');
  24. var gOPD = Object.getOwnPropertyDescriptor;
  25. var regexClass = '[object RegExp]';
  26. module.exports = hasToStringTag
  27. // eslint-disable-next-line consistent-return
  28. ? function isRegex(value) {
  29. if (!value || typeof value !== 'object') {
  30. return false;
  31. }
  32. var descriptor = gOPD(value, 'lastIndex');
  33. var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
  34. if (!hasLastIndexDataProperty) {
  35. return false;
  36. }
  37. try {
  38. $exec(value, badStringifier);
  39. } catch (e) {
  40. return e === isRegexMarker;
  41. }
  42. }
  43. : function isRegex(value) {
  44. // In older browsers, typeof regex incorrectly returns 'function'
  45. if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
  46. return false;
  47. }
  48. return $toString(value) === regexClass;
  49. };