-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (76 loc) · 2.76 KB
/
index.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
/* global module,require,process */
'use strict';
var fs = require('fs'),
counter = {
getSelectorCount: function(line) {
var selectorString,
selectors;
// even with @media queries, this still works
// get the selector
selectorString = line.trim().split('{')[0];
// split selectors and get the length
selectors = selectorString.split(',');
return selectors ? selectors.length : 0;
},
getDeclarationCount: function(line) {
var declarationString,
declarations,
i,
count = 0;
// get the rules
// before: #test { background-color: blue;
// after: [ '#test ', 'background-color: blue;' ]
declarationString = line.trim().split('{')[1];
// split rules and get the length:
// before: background-color: blue;
// after: [ ' background-color: blue', '' ]
if (declarationString) {
declarations = declarationString.split(';');
// check for any empty strings on split
i = declarations.length;
while (i--) {
if (declarations[i]) {
count++;
}
}
}
return count;
},
getMediaQueryCount: function(line) {
return (line.indexOf('@media') === -1) ? 0 : 1;
},
analyze: function(fileContents) {
var blocks = 0,
selectors = 0,
declarations = 0,
mediaQueries = 0;
fileContents.split('}').forEach(function(line) {
if (line) {
line += '}';
selectors += this.getSelectorCount(line);
declarations += this.getDeclarationCount(line);
mediaQueries += this.getMediaQueryCount(line);
blocks++;
}
}.bind(this));
return {
selectors: selectors,
declarationBlocks: blocks,
declarations: declarations,
mediaQueries: mediaQueries
};
},
analyzeFile: function(filepath, callback) {
if (!filepath) {
throw new Error('no file specified.');
}
if (!callback) {
throw new Error('no callback passed in.');
}
fs.readFile(filepath, function(err, data) {
if (err) { throw err; }
callback(this.analyze(data.toString()));
}.bind(this));
}
};
module.exports = counter;