-
Notifications
You must be signed in to change notification settings - Fork 0
/
01_basic.test.ts
74 lines (68 loc) · 2.22 KB
/
01_basic.test.ts
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
69
70
71
72
73
74
import { LoroDoc, LoroList, LoroMap, LoroText } from "npm:[email protected]";
import { expect } from "npm:[email protected]";
Deno.test("Basic usage", () => {
/**
* LoroDoc is the entry point for using Loro.
* You must create a Doc to use Map, List, Text, and other CRDT types.
*/
const doc = new LoroDoc();
const list: LoroList = doc.getList("list");
list.insert(0, "A");
list.insert(1, "B");
list.insert(2, "C"); // ["A", "B", "C"]
const map: LoroMap = doc.getMap("map");
// map can only has string key
map.set("key", "value");
expect(doc.toJSON()).toStrictEqual({
list: ["A", "B", "C"],
map: { key: "value" },
});
// delete 2 element at index 0
list.delete(0, 2);
expect(doc.toJSON()).toStrictEqual({
list: ["C"],
map: { key: "value" },
});
});
Deno.test("Sub containers", () => {
/**
* You can create sub CRDT containers in List and Map.
*/
const doc = new LoroDoc();
const list: LoroList = doc.getList("list");
const map: LoroMap = doc.getMap("list");
// insert a List container at index 0, and get the handler to that list
const subList = list.insertContainer(0, new LoroList());
subList.insert(0, "A");
expect(list.toJSON()).toStrictEqual([["A"]]);
// create a Text container inside the Map container
const subtext = map.setContainer("text", new LoroText());
subtext.insert(0, "Hi");
expect(map.toJSON()).toStrictEqual({ text: "Hi" });
});
Deno.test("Sync", () => {
/**
* Two documents can complete synchronization with two rounds of exchanges.
*/
const docA = new LoroDoc();
const docB = new LoroDoc();
const listA: LoroList = docA.getList("list");
listA.insert(0, "A");
listA.insert(1, "B");
listA.insert(2, "C");
// B import the ops from A
docB.import(docA.export({ mode: "update" }));
expect(docB.toJSON()).toStrictEqual({
list: ["A", "B", "C"],
});
const listB: LoroList = docB.getList("list");
// delete 1 element at index 1
listB.delete(1, 1);
// A import the missing ops from B
docA.import(docB.export({ mode: "update", from: docA.version() }));
// list at A is now ["A", "C"], with the same state as B
expect(docA.toJSON()).toStrictEqual({
list: ["A", "C"],
});
expect(docA.toJSON()).toStrictEqual(docB.toJSON());
});