index.js 988 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. var toString = Object.prototype.toString;
  3. /**
  4. * Extract names from functions.
  5. *
  6. * @param {Function} fn The function who's name we need to extract.
  7. * @returns {String} The name of the function.
  8. * @public
  9. */
  10. module.exports = function name(fn) {
  11. if ('string' === typeof fn.displayName && fn.constructor.name) {
  12. return fn.displayName;
  13. } else if ('string' === typeof fn.name && fn.name) {
  14. return fn.name;
  15. }
  16. //
  17. // Check to see if the constructor has a name.
  18. //
  19. if (
  20. 'object' === typeof fn
  21. && fn.constructor
  22. && 'string' === typeof fn.constructor.name
  23. ) return fn.constructor.name;
  24. //
  25. // toString the given function and attempt to parse it out of it, or determine
  26. // the class.
  27. //
  28. var named = fn.toString()
  29. , type = toString.call(fn).slice(8, -1);
  30. if ('Function' === type) {
  31. named = named.substring(named.indexOf('(') + 1, named.indexOf(')'));
  32. } else {
  33. named = type;
  34. }
  35. return named || 'anonymous';
  36. };