Get first row and column of diff using Google Diff Match Patch?

477 Views Asked by At

I'm following the example at https://github.com/google/diff-match-patch and

var text = "<div class='hover'>\nHello world\n</div>";
var text2 = "<div class='hover'>\nHello whirld\n</div>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);

When I look at the object the result is:

Array {
  0     0,<div class='hover'>
Hello w
  1     -1,o
  2     1,hi
  3     0,rld
</div>
}

The documentation says it returns an array of tuples. How can I get the row number and line number of the first difference? If I'm able to get the first change that's a bonus but not required.

After creating the example above it looks like I can find the first -1 and that is the row? I was hoping for a method that did something like this:

var result = dmp.diff_main(text, text2, false);

Object {
   row: 1,
   column: 4,
   original: "hello world",
   changed: "hello whirld"
}

If I change the 3rd line this is the result:

var text = "<div class='hover'>\nHello world\n</div>";
var text2 = "<div class='hover'>\nHello world\n</div2>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);

This is the result:

Array {
  0     0,<div class='hover'>
Hello world
</div
  1     1,2
  2     0,>
}

So it appears the result does not have line numbers?

https://github.com/google/diff-match-patch

1

There are 1 best solutions below

0
On BEST ANSWER

This sort of works:

var text = "<div class='hover'>\nHello world\n</div>";
var text2 = "<div class='hover'>\nHello world\n</div2>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);

var LINE_BREAK = "\n";
var lines = [];
var row = 1;
var column = 0;
var firstResult = result && result[0] ? result[0] : null;
var operation = firstResult ? firstResult[0] : null;
var data = firstResult ? firstResult[1] : null;
var lastLine = "";

if (data && data.indexOf(LINE_BREAK)!=-1) {
    lines = data.split(LINE_BREAK);
    lastLine = lines[lines.length-1];
    row = lines.length;
    column = lastLine.length;
}