1 import * as Y from 'yjs'
3 describe('SquashAlgorithm', () => {
4 describe('yjs merge', () => {
5 const harvestUpdates = async (doc: Y.Doc, count: number): Promise<Uint8Array[]> => {
6 return new Promise((resolve) => {
7 const updates: Uint8Array[] = []
9 doc.on('update', (update) => {
12 if (updates.length === count) {
19 it('should be able to merge a single update', async () => {
20 const doc = new Y.Doc()
22 const updatesPromise = harvestUpdates(doc, 1)
24 doc.getText().insert(0, 'H')
26 const updates = await updatesPromise
28 const squashed = Y.mergeUpdates(updates)
30 const reassembledDoc = new Y.Doc()
31 Y.applyUpdate(reassembledDoc, squashed)
33 expect(reassembledDoc.getText().toString()).toEqual('H')
36 it('should be able to merge multiple updates', async () => {
37 const doc = new Y.Doc()
39 const updatesPromise = harvestUpdates(doc, 3)
41 doc.getText().insert(0, 'H')
42 doc.getText().insert(1, 'e')
43 doc.getText().insert(2, 'y')
45 const updates = await updatesPromise
47 const squashed = Y.mergeUpdates(updates)
49 const reassembledDoc = new Y.Doc()
50 Y.applyUpdate(reassembledDoc, squashed)
52 expect(reassembledDoc.getText().toString()).toEqual('Hey')
55 it('should be able to merge only a tail subset of updates', async () => {
56 const doc = new Y.Doc()
58 const updatesPromise = harvestUpdates(doc, 5)
60 doc.getText().insert(0, 'H')
61 doc.getText().insert(1, 'e')
62 doc.getText().insert(2, 'l')
63 doc.getText().insert(3, 'l')
64 doc.getText().insert(4, 'o')
66 const updates = await updatesPromise
68 const squashed = Y.mergeUpdates(updates.slice(-2))
70 const reassembledDoc = new Y.Doc()
71 for (const update of updates.slice(0, 3)) {
72 Y.applyUpdate(reassembledDoc, update)
74 Y.applyUpdate(reassembledDoc, squashed)
76 expect(reassembledDoc.getText().toString()).toEqual('Hello')
79 it('should be able to merge only a tail subset of updates with originals being squashed as well', async () => {
80 const doc = new Y.Doc()
82 const updatesPromise = harvestUpdates(doc, 5)
84 doc.getText().insert(0, 'H')
85 doc.getText().insert(1, 'e')
86 doc.getText().insert(2, 'l')
87 doc.getText().insert(3, 'l')
88 doc.getText().insert(4, 'o')
90 const updates = await updatesPromise
92 const squashed = Y.mergeUpdates(updates.slice(-2))
94 const reassembledDoc = new Y.Doc()
96 Y.applyUpdate(reassembledDoc, Y.mergeUpdates(updates.slice(0, 3)))
97 Y.applyUpdate(reassembledDoc, squashed)
99 expect(reassembledDoc.getText().toString()).toEqual('Hello')