Skip to content

Commit 46413d5

Browse files
committed
docs: op and change
1 parent 8338c05 commit 46413d5

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

10_op_and_change.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { Change, Loro, LoroList, LoroText } from "npm:[email protected]";
2+
import { expect } from "npm:[email protected]";
3+
4+
Deno.test("op and change", () => {
5+
const docA = new Loro();
6+
docA.setPeerId("0");
7+
const textA = docA.getText("text");
8+
// This create 3 operations
9+
textA.insert(0, "123");
10+
// This create a new Change
11+
docA.commit();
12+
// This create 2 operations
13+
textA.insert(0, "ab");
14+
// This will NOT create a new Change
15+
docA.commit();
16+
17+
{
18+
const changeMap: Map<`${number}`, Change[]> = docA.getAllChanges();
19+
expect(changeMap.size).toBe(1);
20+
expect(changeMap.get("0")).toStrictEqual([
21+
{
22+
lamport: 0,
23+
length: 5,
24+
peer: "0",
25+
counter: 0,
26+
deps: [],
27+
timestamp: 0,
28+
},
29+
]);
30+
}
31+
32+
// Create docB from doc
33+
const docB = Loro.fromSnapshot(docA.exportSnapshot());
34+
docB.setPeerId("1");
35+
const textB = docB.getText("text");
36+
// This create 2 operations
37+
textB.insert(0, "cd");
38+
39+
// Import the Change from docB to doc
40+
const bytes = docB.exportFrom(); // Exporting has implicit commit
41+
docA.import(bytes);
42+
43+
// This create 1 operations
44+
textA.insert(0, "1");
45+
// Because doc import a Change from docB, it will create a new Change for
46+
// new commit to record this causal order
47+
docA.commit();
48+
{
49+
const changeMap: Map<`${number}`, Change[]> = docA.getAllChanges();
50+
expect(changeMap.size).toBe(2);
51+
expect(changeMap.get("0")).toStrictEqual([
52+
{
53+
lamport: 0,
54+
length: 5,
55+
peer: "0",
56+
counter: 0,
57+
deps: [],
58+
timestamp: 0,
59+
},
60+
{
61+
lamport: 7,
62+
length: 1,
63+
peer: "0",
64+
counter: 5,
65+
deps: [{ peer: "1", counter: 1 }],
66+
timestamp: 0,
67+
},
68+
]);
69+
expect(changeMap.get("1")).toStrictEqual([
70+
{
71+
lamport: 5,
72+
length: 2,
73+
peer: "1",
74+
counter: 0,
75+
deps: [{ peer: "0", counter: 4 }],
76+
timestamp: 0,
77+
},
78+
]);
79+
}
80+
});

0 commit comments

Comments
 (0)