-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcss-simplify.js
executable file
·81 lines (64 loc) · 1.88 KB
/
css-simplify.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
#!/usr/bin/env node
var css = require('css'),
fs = require('fs'),
_ = require('underscore');
var cumulativeComparisonVectorFactoryFactory = function() {
var dict = {},
dictlength = 0;
return function(rule) {
var vector = Array.apply(null, Array(dictlength)).map(Number.prototype.valueOf, 0);
_.each(rule.selectors, function(element){
if (dict[element]) {
vector[dict[element]] = 1;
}else {
dict[element] = dictlength++;
vector.push(1);
}
});
return { 'vector': vector, 'rule': rule };
};
};
var safeCosineSimilarity = function(a, b) {
var result = 0, denom = 0;
for (var i = 0; i < a.length && i < b.length; ++i ) {
result += a[i] * b[i];
}
var reducer = function(memo, value) { return memo + value * value; };
return result / (1+ Math.sqrt( _.reduce(a, reducer, 0) * _.reduce(b, reducer, 0) ));
};
var rankVectors = function (vectors) {
// how can we save time and computations when doing the comparisons? can we?
// what are we really looking for, how do we find the most similar things?
var ranks = [],
length = vectors.length;
for (var j = 0; j < length; ++j ) {
ranks[j] = [];
for (var i = 0; i <= j; ++i) {
if ( i === j ) {
ranks[j][i] = 0;
continue;
}
ranks[j][i] = safeCosineSimilarity(vectors[i], vectors[j]);
}
}
return ranks;
};
var vecfac = cumulativeComparisonVectorFactoryFactory(),
processedRules = null,
vectors = null;
// lets go:
fs.readFile('lol.css', 'utf8', function (err, res) {
if (res !== null) {
processedRules = _.map(_.filter(css.parse(res).stylesheet.rules, function(x) { return x.type === 'rule';}), vecfac);
} else {
console.log('ERROR');
console.log(err);
}
vectors = _.map(processedRules, function(rule) { return rule.vector });
if (vectors === null) {
console.log('vectors is null');
process.exit();
}
var rankedVectors = rankVectors(vectors);
console.log(rankedVectors);
});