blob: e4aa58241d9e4521dd022a588e42bb8b878fea92 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001'use strict';
2
3/* !
4 * Chai - getFuncName utility
5 * Copyright(c) 2012-2016 Jake Luer <jake@alogicalparadox.com>
6 * MIT Licensed
7 */
8
9/**
10 * ### .getFuncName(constructorFn)
11 *
12 * Returns the name of a function.
13 * When a non-function instance is passed, returns `null`.
14 * This also includes a polyfill function if `aFunc.name` is not defined.
15 *
16 * @name getFuncName
17 * @param {Function} funct
18 * @namespace Utils
19 * @api public
20 */
21
22var toString = Function.prototype.toString;
23var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/;
24function getFuncName(aFunc) {
25 if (typeof aFunc !== 'function') {
26 return null;
27 }
28
29 var name = '';
30 if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') {
31 // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined
32 var match = toString.call(aFunc).match(functionNameMatch);
33 if (match) {
34 name = match[1];
35 }
36 } else {
37 // If we've got a `name` property we just use it
38 name = aFunc.name;
39 }
40
41 return name;
42}
43
44module.exports = getFuncName;