Repository navigation
Expand file tree
/
Copy pathdiff.ts
More file actions
68 lines (58 loc) · 1.93 KB
/
Copy pathdiff.ts
File metadata and controls
68 lines (58 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// deno-lint-ignore-file no-explicit-any
import { createStringDelta } from './_delta.ts';
export type Patch = {
op: 'replace' | 'remove' | 'add' | 'delta';
path: (string | number)[];
value?: any;
};
function keys(x: any): string[] | number[] {
if (Array.isArray(x)) {
return new Array(x.length).fill(0).map((_, i) => i);
}
return Object.keys(x);
}
export default function *diff(x: any, y: any, path: (string | number)[] = []): Generator<Patch> {
if (x === y) {
return;
}
const [ xKeys, yKeys ] = [ keys(x), keys(y) ];
const [ xIsArray, yIsArray ] = [ Array.isArray(x), Array.isArray(y) ];
let deleted = false;
for (const key of xKeys.reverse()) {
const newPath = [ ...path, key ];
const oldValue = x[key];
if (Object.hasOwn(y, key) && !(y[key] === undefined && oldValue !== undefined && !xIsArray)) {
const newValue = y[key];
if (typeof oldValue === 'object' && oldValue !== null && typeof newValue === 'object' && newValue !== null && Array.isArray(oldValue) === Array.isArray(newValue)) {
yield *diff(oldValue, newValue, newPath);
} else if (oldValue !== newValue) {
if (typeof oldValue === 'string' && typeof newValue === 'string' && newValue.length >= 64) {
yield { op: 'delta', path: newPath, value: createStringDelta(oldValue, newValue) };
} else {
yield { op: 'replace', path: newPath, value: newValue };
}
}
} else if (xIsArray === yIsArray) {
yield { op: 'remove', path: newPath };
deleted = true;
} else {
yield { op: 'replace', path, value: x };
}
}
if (!deleted && yKeys.length === xKeys.length) {
return;
}
for (const key of yKeys) {
if (!Object.hasOwn(x, key) && y[key] !== undefined) {
yield { op: 'add', path: [ ...path, key ], value: y[key] };
}
}
}
export class DiffTracker {
constructor(private lastValue: any = {}) {}
update(value: any): Patch[] {
const patches = [ ...diff(this.lastValue, value) ];
this.lastValue = value;
return patches;
}
}