-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhalcsstead.js
99 lines (78 loc) · 2.18 KB
/
halcsstead.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var css = require('css');
var cssSelectorTree = require('css-selector-tree');
var unique = require('array-unique');
function calculcateSelectorMetrics (selector) {
if (!selector) {
return false;
}
var conditions = cssSelectorTree.conditions(selector);
if (conditions === false) {
return false;
}
var uniqueOperators = 5; // if, (, ), {, }
var operatorsPerItem = 7; // e.g. »IF (is_pseudo_element('first-line')) { … }«
var totalOperators = operatorsPerItem * conditions.length;
var operands = [];
conditions.forEach(function (item) {
if (item.type === 'child') {
operands.push('is_child');
} else if (item.type === 'operator') {
operands.push('is_' + item.operator);
} else {
operands.push('is_' + item.type);
operands.push(item.name);
}
});
var totalOperands = operands.length;
var uniqueOperands = unique(operands).length;
var vocabulary = (uniqueOperators + uniqueOperands);
var length = (totalOperators + totalOperands);
var volume = Math.ceil(length * Math.log(vocabulary) / Math.LN2);
var difficulty = (uniqueOperators * uniqueOperands);
var effort = (difficulty * volume);
return {
uniqueOperators: uniqueOperators,
uniqueOperands: uniqueOperands,
totalOperators: totalOperators,
totalOperands: totalOperands,
vocabulary: vocabulary,
length: length,
volume: volume,
difficulty: difficulty,
effort: effort
};
}
function parseCss (code) {
if (!code) {
return false;
}
var obj;
var results = [];
try {
obj = css.parse(code);
} catch (e) {
return false;
}
if (obj.stylesheet && obj.stylesheet.rules) {
obj.stylesheet.rules.forEach(function (rule) {
if (rule.selectors && rule.selectors.length) {
rule.selectors.forEach(function (selector) {
results.push({
selector: selector,
metrics: calculcateSelectorMetrics(selector)
});
});
}
});
}
if (!results.length) {
return false;
}
return results.sort(function (a, b) {
return a.metrics.effort - b.metrics.effort;
}).reverse();
}
module.exports = {
selector: calculcateSelectorMetrics,
parse: parseCss
};