Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Created August 15, 2017 00:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addyosmani/4bd8d89fa447dd38a02c92c022b6cbca to your computer and use it in GitHub Desktop.
Save addyosmani/4bd8d89fa447dd38a02c92c022b6cbca to your computer and use it in GitHub Desktop.
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;
};
@probil
Copy link

probil commented Dec 9, 2021

FYI: The one from Google DevTools is much faster:
https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/models/text_utils/TextUtils.ts#L336

small not minified file (5kb)

$ node benchmark.js

isMinified#FF x 213,571 ops/sec ±0.42% (89 runs sampled)
isMinified#Google x 1,196,225 ops/sec ±0.22% (91 runs sampled)
Fastest is isMinified#Google

angular.min.js (173Kb)

$ node benchmark.js

isMinified#FF x 3,861 ops/sec ±0.33% (92 runs sampled)
isMinified#Google x 7,116,082 ops/sec ±0.16% (92 runs sampled)
Fastest is isMinified#Google

angular.js (1.3Mb)

node benchmark.js

isMinified#FF x 460 ops/sec ±7.02% (80 runs sampled)
isMinified#Google x 850,793 ops/sec ±0.45% (93 runs sampled)
Fastest is isMinified#Google

But not as reliable, when there is eval() usage with unminified code inside FF version says it's not minified (which is truth) while the one from google dev tools says it is. But that's rather an edge case scenario

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment