Skip to content

Instantly share code, notes, and snippets.

@harthur
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harthur/c6c939a938db52064a7a to your computer and use it in GitHub Desktop.
Save harthur/c6c939a938db52064a7a to your computer and use it in GitHub Desktop.
Compare lines indentation detection
function detectIndent(lines) {
var indents = {}; // # spaces indent -> # times seen
var last = 0; // # leading spaces in the last line we saw
lines.forEach(function (text) {
var width = leadingSpaces(text);
var indent = Math.abs(width - last);
if (indent > 1) {
indents[indent] = (indents[indent] || 0) + 1;
}
last = width;
});
// find most frequent non-zero width difference
var indent = null, max = 0;
for (var width in indents) {
width = parseInt(width, 10);
var tally = indents[width];
if (tally > max) {
max = tally;
indent = width;
}
}
return indent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment