Created
June 16, 2015 20:36
-
-
Save vmakhaev/4d0c7574e981faeb5e36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chars = 'abcdefghijklmopquwxyz'; | |
//var c = ['block_sss', 'elem__asdf', 'footer__container', 'title', 'title__child','title__child','title__child','title__child']; | |
var parts = []; | |
function minify(classNames) { | |
var names = []; | |
for (var i = 0; i < classNames.length; i++) { | |
var className = classNames[i]; | |
if (names[className]) { | |
names[className]++; | |
} else { | |
names[className] = 1; | |
} | |
} | |
var max = 0; | |
var namesByCount = {}; | |
for (var name in names) { | |
var count = names[name]; | |
max = Math.max(max, count); | |
var key = count.toString(); | |
if (namesByCount[key]) { | |
namesByCount[key].push(name); | |
} else { | |
namesByCount[key] = [name]; | |
} | |
} | |
var sortedClassNames = []; | |
for (var i = max; i > 0; i--) { | |
var key = i.toString(); | |
if (namesByCount[key]) { | |
sortedClassNames = sortedClassNames.concat(namesByCount[key]); | |
} | |
} | |
// here we got array of classes, sorted by number of their appearance | |
var minifiedNames = {}; | |
for (var i = 0; i < sortedClassNames.length; i++) { | |
var className = sortedClassNames[i]; | |
var minifiedName = getMinifiedName(); | |
minifiedNames[className] = minifiedName; | |
} | |
//console.log(minifiedNames); | |
return minifiedNames; | |
} | |
function getMinifiedName() { | |
var lastPartIndex = parts.length - 1; | |
function incPart(index) { | |
var part = parts[index]; | |
if (!part) { | |
for (var i = 0; i <= lastPartIndex + 1; i++) { | |
parts[i] = 'a'; | |
} | |
} else { | |
var i = chars.indexOf(part); | |
i++; | |
if (i === chars.length) { | |
parts[index] = 'a'; | |
incPart(index - 1); | |
} else { | |
parts[index] = chars[i]; | |
} | |
} | |
} | |
incPart(lastPartIndex); | |
return parts.join(''); | |
} | |
module.exports = minify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment