Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Detecting unminified code
// https://hg.mozilla.org/mozilla-central/rev/2f9043292e63
// Used to detect minification for automatic pretty printing
const SAMPLE_SIZE = 30; // no of lines
const INDENT_COUNT_THRESHOLD = 20; // percentage
function isMinified (str) {
let isMinified;
let lineEndIndex = 0;
let lineStartIndex = 0;
let lines = 0;
let indentCount = 0;
// Strip comments.
str = str.replace(/\/\*[\S\s]*?\*\/|\/\/(.+|\n)/g, "");
while (lines++ < SAMPLE_SIZE) {
lineEndIndex = str.indexOf("\n", lineStartIndex);
if (lineEndIndex == -1) {
break;
}
if (/^\s+/.test(str.slice(lineStartIndex, lineEndIndex))) {
indentCount++;
}
lineStartIndex = lineEndIndex + 1;
}
isMinified = ((indentCount / lines ) * 100) < INDENT_COUNT_THRESHOLD;
return isMinified;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.