index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var fnToStr = Function.prototype.toString;
  3. var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
  4. var badArrayLike;
  5. var isCallableMarker;
  6. if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
  7. try {
  8. badArrayLike = Object.defineProperty({}, 'length', {
  9. get: function () {
  10. throw isCallableMarker;
  11. }
  12. });
  13. isCallableMarker = {};
  14. // eslint-disable-next-line no-throw-literal
  15. reflectApply(function () { throw 42; }, null, badArrayLike);
  16. } catch (_) {
  17. if (_ !== isCallableMarker) {
  18. reflectApply = null;
  19. }
  20. }
  21. } else {
  22. reflectApply = null;
  23. }
  24. var constructorRegex = /^\s*class\b/;
  25. var isES6ClassFn = function isES6ClassFunction(value) {
  26. try {
  27. var fnStr = fnToStr.call(value);
  28. return constructorRegex.test(fnStr);
  29. } catch (e) {
  30. return false; // not a function
  31. }
  32. };
  33. var tryFunctionObject = function tryFunctionToStr(value) {
  34. try {
  35. if (isES6ClassFn(value)) { return false; }
  36. fnToStr.call(value);
  37. return true;
  38. } catch (e) {
  39. return false;
  40. }
  41. };
  42. var toStr = Object.prototype.toString;
  43. var fnClass = '[object Function]';
  44. var genClass = '[object GeneratorFunction]';
  45. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  46. module.exports = reflectApply
  47. ? function isCallable(value) {
  48. if (!value) { return false; }
  49. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  50. if (typeof value === 'function' && !value.prototype) { return true; }
  51. try {
  52. reflectApply(value, null, badArrayLike);
  53. } catch (e) {
  54. if (e !== isCallableMarker) { return false; }
  55. }
  56. return !isES6ClassFn(value);
  57. }
  58. : function isCallable(value) {
  59. if (!value) { return false; }
  60. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  61. if (typeof value === 'function' && !value.prototype) { return true; }
  62. if (hasToStringTag) { return tryFunctionObject(value); }
  63. if (isES6ClassFn(value)) { return false; }
  64. var strClass = toStr.call(value);
  65. return strClass === fnClass || strClass === genClass;
  66. };