MCPcopy
hub / github.com/loggerhead/json4u / arrayDiff

Function arrayDiff

src/lib/compare/myers.ts:18–75  ·  view source on GitHub ↗
(
  lvals: T[],
  rvals: T[],
  options?: DiffOptions,
)

Source from the content-addressed store, hash-verified

16 * @returns An array of differences.
17 */
18export function arrayDiff<T extends number | string | boolean | null>(
19 lvals: T[],
20 rvals: T[],
21 options?: DiffOptions,
22): Diff[] {
23 const lineArray = [""];
24 const lineHash: Record<string, number> = {};
25 let n = lineArray.length;
26
27 // Maps an array of lines to a string of unicode characters, then performs a text compare.
28 const lines2chars = (lines: string[]) => {
29 const baseChar = "0".charCodeAt(0);
30 let chars = "";
31
32 for (const line of lines) {
33 if (lineHash.hasOwnProperty(line)) {
34 chars += String.fromCharCode(baseChar + lineHash[line]);
35 } else {
36 chars += String.fromCharCode(baseChar + n);
37 lineHash[line] = n;
38 lineArray[n++] = line;
39 }
40 }
41
42 return chars;
43 };
44
45 // Each line is an array element.
46 const llines = lvals.map(String);
47 const rlines = rvals.map(String);
48 // Each character is an array element.
49 const lchars = lines2chars(llines);
50 const rchars = lines2chars(rlines);
51 let lpos = 0;
52 let rpos = 0;
53 const diffs: Diff[] = [];
54
55 diff(lchars, rchars, { ...options, isArrayDiff: true }).forEach((d) => {
56 const n = d.value?.length!;
57
58 if (d.removed) {
59 for (let i = 0; i < n; i++) {
60 diffs.push(newDiff(lpos, 1, "del"));
61 lpos++;
62 }
63 } else if (d.added) {
64 for (let i = 0; i < n; i++) {
65 diffs.push(newDiff(rpos, 1, "ins"));
66 rpos++;
67 }
68 } else {
69 lpos += n;
70 rpos += n;
71 }
72 });
73
74 return diffs;
75}

Callers 1

compareArrayFunction · 0.90

Calls 3

newDiffFunction · 0.90
lines2charsFunction · 0.85
diffFunction · 0.70

Tested by

no test coverage detected