'use strict';
var repeating = require('repeating');
var INDENT_RE = /^(?:( )+|\t+)/;
function getMostUsed(indents) {
var result = 0;
var maxUsed = 0;
var maxWeight = 0;
for (var n in indents) {
var indent = indents[n];
var u = indent[0];
var w = indent[1];
if (u > maxUsed || u === maxUsed && w > maxWeight) {
maxUsed = u;
maxWeight = w;
result = Number(n);
}
}
return result;
}
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
var tabs = 0;
var spaces = 0;
var prev = 0;
var indents = {};
var current;
var isIndent;
str.split(/\n/g).forEach(function (line) {
if (!line) {
return;
}
var indent;
var matches = line.match(INDENT_RE);
if (!matches) {
indent = 0;
} else {
indent = matches[0].length;
if (matches[1]) {
spaces++;
} else {
tabs++;
}
}
var diff = indent - prev;
prev = indent;
if (diff) {
isIndent = diff > 0;
current = indents[isIndent ? diff : -diff];
if (current) {
current[0]++;
} else {
current = indents[diff] = [1, 0];
}
} else if (current) {
current[1] += Number(isIndent);
}
});
var amount = getMostUsed(indents);
var type;
var actual;
if (!amount) {
type = null;
actual = '';
} else if (spaces >= tabs) {
type = 'space';
actual = repeating(' ', amount);
} else {
type = 'tab';
actual = repeating('\t', amount);
}
return {
amount: amount,
type: type,
indent: actual
};
};