Skip to content

Commit

Permalink
Fix detecting the indent of files with many repeats after a single in…
Browse files Browse the repository at this point in the history
…dent (#34)
  • Loading branch information
gwhitney committed Sep 11, 2022
1 parent 6062d95 commit 477e390
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
43 changes: 43 additions & 0 deletions fixture/long-repeat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
/* Examine the case of an indent that happens only once
but then has a long block at that level, as compared to
an indent that occurs many times.
The odd spacing on this line is artificial, but critical to the example. */
observation: 'This is literally the only line with a 1-space change',
key1: 'dummy',
key2: 'dummy',
key3: 'dummy',
key4: 'dummy',
key5: 'dummy',
key6: 'dummy',
key7: 'dummy',
key8: 'dummy',
key9: 'dummy',
key10: 'dummy',
key11: 'dummy',
key12: 'dummy',
key13: 'dummy',
key14: 'dummy',
key15: 'dummy',
key16: 'dummy',
key17: 'dummy',
key18: 'dummy',
key19: 'dummy',
key20: 'dummy',
contrast: {
idea: 'Now we will have about ten instances with an indent change of 4',
},
contrast2: {
subkey: 'dummy'
},
contrast3: {
subkey: 'dummy'
},
contrast4: {
subkey: 'dummy'
},
contrast5: {
subkey: 'dummy'
},
}

9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function makeIndentsMap(string, ignoreSingleSpaces) {

let indent;
let indentType;
let use;
let weight;
let entry;
const matches = line.match(INDENT_REGEX);
Expand All @@ -58,14 +59,18 @@ function makeIndentsMap(string, ignoreSingleSpaces) {

previousIndentType = indentType;

use = 1;
weight = 0;

const indentDifference = indent - previousSize;
previousSize = indent;

// Previous line have same indent?
if (indentDifference === 0) {
weight++;
// Not a new "use" of the current indent:
use = 0;
// But do add a bit to it for breaking ties:
weight = 1;
// We use the key from previous loop
} else {
const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
Expand All @@ -74,7 +79,7 @@ function makeIndentsMap(string, ignoreSingleSpaces) {

// Update the stats
entry = indents.get(key);
entry = entry === undefined ? [1, 0] : [++entry[0], entry[1] + weight];
entry = entry === undefined ? [1, 0] : [entry[0] + use, entry[1] + weight];

indents.set(key, entry);
}
Expand Down
5 changes: 5 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,8 @@ test('return indentations status for indented files with single spaces only', t
type: 'space',
});
});

test('detect the indent of a file with many repeats after a single indent', t => {
const stats = detectIndent(getFile('fixture/long-repeat.js'));
t.is(stats.amount, 4);
});

0 comments on commit 477e390

Please sign in to comment.