forked from xiemaisi/acg.js
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcallbackCounter.js
More file actions
76 lines (66 loc) · 3.09 KB
/
callbackCounter.js
File metadata and controls
76 lines (66 loc) · 3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define(function(require, exports) {
var astutil = require('./astutil'),
graph = require('./graph');
exports.countCallbacks = function(ast) {
var callbacks = [], callbackUses = 0;
var enclosingFunctionParameters = [];
var functionDeclarationParameter = 0, functionExpressionParameter = 0;
astutil.visit(ast, function(node) {
switch (node.type) {
case 'CallExpression' :
//FIND ARGUMENT AS PARAMETER IN ENCLOSING FUNCTION.
var callee = node.callee, functionName = callee.name;
var enclosingFunctionParameter = findEnclosingFunctionParameter(callee, functionName);
if (enclosingFunctionParameter !== null) {
callbackUses++;
if (enclosingFunctionParameters.indexOf(enclosingFunctionParameter) === -1) {
callbacks.push(node);
enclosingFunctionParameters.push(enclosingFunctionParameter);
}
}
break;
case 'FunctionDeclaration' :
functionDeclarationParameter += node.params.length;
break;
case 'FunctionExpression' :
functionExpressionParameter += node.params.length;
break;
}
});
var totalParameters = functionDeclarationParameter + functionExpressionParameter;
var callbackPercentage = callbacks.length / totalParameters * 100;
console.log("I found " + callbacks.length + " callbacks and " + callbackUses + " call back uses. In total we have " + functionDeclarationParameter + " function declaration parameters and " + functionExpressionParameter + " function expression parameters.");
console.log("This makes a total of " + totalParameters + " parameters. Which means that (counting each function once as a callback) " + callbackPercentage + " percent of parameters are callbacks.");
console.log("The total SLOC is " + ast.attr.sloc);
};
function findEnclosingFunctionParameter(node, functionName) {
var enclosingFunction = node.attr.enclosingFunction;
if (!enclosingFunction) {
return null;
}
var matchingParameter = findFirst(enclosingFunction.params, isParameterWithName(functionName));
if (matchingParameter !== null) {
return matchingParameter;
}
return findEnclosingFunctionParameter(enclosingFunction, functionName);
}
function findFirst(array, predicate) {
var soughtElement = null;
array.forEach(function(element) {
if (predicate(element) === true) {
soughtElement = element;
return false;
}
});
return soughtElement;
}
function isParameterWithName(functionName) {
return function(parameter) {
return parameter.name === functionName;
};
}
return exports;
});