MCPcopy Index your code
hub / github.com/danvk/webdiff / computeCharacterDiffs

Function computeCharacterDiffs

ts/codediff/char-diffs.ts:20–81  ·  view source on GitHub ↗
(
  beforeText: string,
  afterText: string,
)

Source from the content-addressed store, hash-verified

18 * character differences are not appropriate for this line pairing.
19 */
20export function computeCharacterDiffs(
21 beforeText: string,
22 afterText: string,
23): [CharacterDiff[], CharacterDiff[]] | null {
24 const beforeWords = splitIntoWords(beforeText);
25 const afterWords = splitIntoWords(afterText);
26 const diffs = Diff.diffArrays(beforeWords, afterWords);
27
28 // Suppress char-by-char diffs if there's less than 50% character overlap.
29 // The one exception is pure whitespace diffs, which should always be shown.
30 const minEqualFrac = 0.5;
31 let equalCount = 0;
32 let charCount = 0;
33 let beforeAllWhitespace = true;
34 let afterAllWhitespace = true;
35 for (const diff of diffs) {
36 const len = strArrayLen(diff.value);
37 if (diff.added) {
38 afterAllWhitespace &&= diff.value.every(allWhitespace);
39 charCount += len;
40 } else if (diff.removed) {
41 beforeAllWhitespace &&= diff.value.every(allWhitespace);
42 charCount += len;
43 } else {
44 // equal
45 equalCount += 2 * len;
46 charCount += 2 * len;
47 if (beforeAllWhitespace || afterAllWhitespace) {
48 const allSpace = diff.value.every(allWhitespace);
49 beforeAllWhitespace &&= allSpace;
50 afterAllWhitespace &&= allSpace;
51 }
52 }
53 }
54 if (equalCount < minEqualFrac * charCount && !(beforeAllWhitespace && afterAllWhitespace)) {
55 return null;
56 }
57
58 let beforeOut: CharacterDiff[] = [];
59 let afterOut: CharacterDiff[] = []; // (span class, start, end) triples
60 let beforeIdx = 0;
61 let afterIdx = 0;
62 for (const diff of diffs) {
63 const len = strArrayLen(diff.value);
64 if (diff.added) {
65 afterOut.push(['insert', afterIdx, afterIdx + len]);
66 afterIdx += len;
67 } else if (diff.removed) {
68 beforeOut.push(['delete', beforeIdx, beforeIdx + len]);
69 beforeIdx += len;
70 } else {
71 beforeOut.push([null, beforeIdx, beforeIdx + len]);
72 afterOut.push([null, afterIdx, afterIdx + len]);
73 beforeIdx += len;
74 afterIdx += len;
75 }
76 }
77 beforeOut = simplifyCodes(beforeOut);

Callers 3

assertCharDiffFunction · 0.90
addCharacterDiffsFunction · 0.85

Calls 3

splitIntoWordsFunction · 0.85
strArrayLenFunction · 0.85
simplifyCodesFunction · 0.85

Tested by 1

assertCharDiffFunction · 0.72