Skip to content

Commit

Permalink
Option to skip space-only patches
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeche committed Nov 14, 2021
1 parent 0151531 commit e324bf2
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,10 @@ function getDiff(from: ParsedModel, to: ParsedModel, options: Options): Diff[] {
];
}

if (options.skipSpace) {
diffs = skipSpace(diffs);
}

if (options.wordPatches) {
diffs = wordBounds(diffs);
}
Expand Down Expand Up @@ -326,3 +330,36 @@ function getChangeThreshold(diffs: Diff[]): number {

return changed / unchanged;
}

function skipSpace(diffs: Diff[]): Diff[] {
const result: Diff[] = [];
let prev: Diff;

diffs.forEach(chunk => {
let canJoin = false;
if (chunk[0] === DIFF_EQUAL) {
// If previous chunk is also a text (whitespace), join it with previous
canJoin = true;
} else if (isSpace(chunk[1])) {
if (chunk[0] === DIFF_DELETE) {
// Skip deleted space chunk
return;
}

chunk[0] = DIFF_EQUAL;
canJoin = true;
}

if (canJoin && prev && prev[0] === DIFF_EQUAL) {
prev[1] += chunk[1];
} else {
result.push(prev = chunk);
}
});

return result;
}

function isSpace(text: string): boolean {
return /^\s+$/.test(text);
}
3 changes: 3 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export interface Options extends ScannerOptions {
/** Normalize whitespace when extracting content from XML */
normalizeSpace?: boolean;

/** Skip space-only diff chunks */
skipSpace?: boolean;

/** Reduce ”noise” by removing meaningless whitespace patches */
compact: boolean;

Expand Down
9 changes: 9 additions & 0 deletions test/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,15 @@ describe('Diff documents', () => {
equal(diff('<p>foo1 baz</p>', '<p>bar1 baz</p>', { replaceThreshold: 0.4 }), '<p><del>foo1 baz</del><ins>bar1 baz</ins></p>');
});

it('skip space patches', () => {
const opt = { skipSpace: true };
equal(diff('<p>foo bar</p>', '<p>foobar</p>'), '<p>foo<del> </del>bar</p>');
equal(diff('<p>foo bar</p>', '<p>foobar</p>', opt), '<p>foobar</p>');

equal(diff('<p>foobar</p>', '<p>foo bar</p>'), '<p>foo<ins> </ins>bar</p>');
equal(diff('<p>foobar</p>', '<p>foo bar</p>', opt), '<p>foo bar</p>');
});

it.skip('debug', () => {
equal(
diff(
Expand Down

0 comments on commit e324bf2

Please sign in to comment.