From da522e390d8a526ba9798b5683d8ae1f32a9b73e Mon Sep 17 00:00:00 2001 From: kpdecker Date: Wed, 26 Aug 2015 03:33:05 -0500 Subject: [PATCH] Special case handling of ignored terminals Fixes #70 --- src/diff/base.js | 12 ++++++++++-- test/diff/word.js | 8 ++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/diff/base.js b/src/diff/base.js index 8d8e14c2..820979df 100644 --- a/src/diff/base.js +++ b/src/diff/base.js @@ -68,7 +68,7 @@ Diff.prototype = { // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) { - return done(buildValues(basePath.components, newString, oldString, self.useLongestToken)); + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; @@ -156,7 +156,7 @@ Diff.prototype = { } }; -function buildValues(components, newString, oldString, useLongestToken) { +function buildValues(diff, components, newString, oldString, useLongestToken) { let componentPos = 0, componentLen = components.length, newPos = 0, @@ -197,6 +197,14 @@ function buildValues(components, newString, oldString, useLongestToken) { } } + // Special case handle for when one terminal is ignored. For this case we merge the + // terminal into the prior string and drop the change. + let lastComponent = components[componentLen - 1]; + if ((lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + return components; } diff --git a/test/diff/word.js b/test/diff/word.js index 41e0de89..d8b6981e 100644 --- a/test/diff/word.js +++ b/test/diff/word.js @@ -77,6 +77,14 @@ describe('WordDiff', function() { expect(diffWords('', 'foo')).to.eql([{value: 'foo', count: 1, added: true, removed: undefined}]); expect(diffWords('', 'foo bar')).to.eql([{value: 'foo bar', count: 3, added: true, removed: undefined}]); }); + + it('should ignore whitespace', function() { + expect(diffWords('hase igel fuchs', 'hase igel fuchs')).to.eql([{ count: 5, value: 'hase igel fuchs' }]); + expect(diffWords('hase igel fuchs', 'hase igel fuchs\n')).to.eql([{ count: 5, value: 'hase igel fuchs\n' }]); + expect(diffWords('hase igel fuchs\n', 'hase igel fuchs')).to.eql([{ count: 5, value: 'hase igel fuchs\n' }]); + expect(diffWords('hase igel fuchs', 'hase igel\nfuchs')).to.eql([{ count: 5, value: 'hase igel\nfuchs' }]); + expect(diffWords('hase igel\nfuchs', 'hase igel fuchs')).to.eql([{ count: 5, value: 'hase igel fuchs' }]); + }); }); describe('#diffWords - async', function() {