index.js 1.4 KB

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