Skip to content

Commit

Permalink
Ignore single space indents (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
brandon93s committed May 28, 2021
1 parent 1808211 commit a1bc058
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
12 changes: 12 additions & 0 deletions fixture/single-space-ignore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
*
* Long
* Multi-line
* Single space
* Comment
*
*/

4 spaces
4 spaces
1 tab
3 changes: 3 additions & 0 deletions fixture/single-space-only.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1 space
1 space
1 space
15 changes: 13 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const INDENT_TYPE_TAB = 'tab';
// s5: [1, 0],
// s12: [1, 0],
// }
function makeIndentsMap(string) {
function makeIndentsMap(string, ignoreSingleSpaces) {
const indents = new Map();

// Remember the size of previous line's indentation
Expand Down Expand Up @@ -49,6 +49,11 @@ function makeIndentsMap(string) {
indentType = INDENT_TYPE_TAB;
}

// Ignore single space unless it's the only indent detected to prevent common false positives
if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) {
continue;
}

if (indentType !== previousIndentType) {
previousSize = 0;
}
Expand Down Expand Up @@ -129,7 +134,13 @@ module.exports = string => {
throw new TypeError('Expected a string');
}

const indents = makeIndentsMap(string);
// Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments)
// If no indents are identified, run again and include all indents for comprehensive detection
let indents = makeIndentsMap(string, true);
if (indents.size === 0) {
indents = makeIndentsMap(string, false);
}

const keyOfMostUsedIndent = getMostUsedKey(indents);

let type;
Expand Down
18 changes: 18 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,21 @@ test('return indentation stats for indented files with spaces and tabs last', t
type: 'tab'
});
});

test('detect the indent of a file with single line comments', t => {
const stats = detectIndent(getFile('fixture/single-space-ignore.js'));
t.deepEqual(stats, {
amount: 4,
indent: ' ',
type: 'space'
});
});

test('return indentations status for indented files with single spaces only', t => {
const stats = detectIndent(getFile('fixture/single-space-only.js'));
t.deepEqual(stats, {
amount: 1,
indent: ' ',
type: 'space'
});
});

0 comments on commit a1bc058

Please sign in to comment.