Skip to content

Commit

Permalink
implement the compact array
Browse files Browse the repository at this point in the history
  • Loading branch information
wewei committed Sep 18, 2024
1 parent cc72920 commit 23b32a1
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 6 deletions.
34 changes: 32 additions & 2 deletions packages/@ot-doc/document/src/lib/array-document.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describeDocumentMeta, DocumentTestCases } from "../util/test-utility";
import { arrayDocument, deleteAt, insertAt, ArrayOplet } from "./array-document";
import { arrayDocument, deleteAt, insertAt, ArrayOplet, compact } from "./array-document";

const arrNum = arrayDocument<number>();

Expand Down Expand Up @@ -48,4 +48,34 @@ describeDocumentMeta('arrayDocument<number>', arrNum, {
// const b_a = comp(b)(a);
// console.log(JSON.stringify(b_a));
},
} as DocumentTestCases<ArrayOplet<number>[]>);
} as DocumentTestCases<ArrayOplet<number>[]>);


const compactArrayNum = compact(arrNum);
describeDocumentMeta('CompactArrayOp<number>', compactArrayNum, {
singleton: [
{},
{
ins: [
{ idx: 0, arr: [1, 2, 3] },
{ idx: 3, arr: [4, 5] },
],
},
{
del: [
{ idx: 3, arr: [4, 5] },
{ idx: 0, arr: [1, 2, 3] },
],
},
{
del: [
{ idx: 3, arr: [4, 5] },
{ idx: 0, arr: [1, 2, 3] },
],
ins: [
{ idx: 0, arr: [5, 4, 3] },
{ idx: 3, arr: [2, 1] },
],
},
],
});
52 changes: 48 additions & 4 deletions packages/@ot-doc/document/src/lib/array-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,56 @@ export function compact<T>(meta: DocumentMeta<ArrayOp<T>>): DocumentMeta<Compact
}, {} as CompactArrayOp<T>);
}

function decompress(op: CompactArrayOp<T>): ArrayOp<T> | undefined {
return meta.comp(
(op.del ?? []).reduce((m, { idx, arr }) => {
m.concat(
arr
.map((val, i): ArrayOplet<T> => ({ typ: 'del', val, idx: idx + i }))
.reverse()
);
return m;
}, [] as ArrayOp<T>)
)(
(op.ins ?? []).reduce((m, { idx, arr }) => {
m.concat(
arr.map(
(val, i): ArrayOplet<T> => ({ typ: 'ins', val, idx: idx + i })
)
);
return m;
}, [] as ArrayOp<T>)
);
}


return {
idn: {},
inv: () => {},
comp: () => () => {},
tran: () => () => {},
equ: () => () => {},
inv: ({ ins, del }) => {
const r: CompactArrayOp<T> = {};
if (ins) {
r.del = [...ins].reverse();
}
if (del) {
r.ins = [...del].reverse();
}
return r;
},
comp: (a) => (b) => {
const dcA = decompress(a);
const dcB = decompress(b);
if (!dcA || !dcB) return undefined;
const dcC = meta.comp(dcA)(dcB);
if (!dcC) return undefined;
return compress(dcC);
},
tran: (a) => (/* b */) => a, // TODO
equ: (a) => (b) => {
if (a === b) return true;
const dcA = decompress(a);
const dcB = decompress(b);
if (dcA && dcB) return meta.equ(dcA)(dcB);
return dcA === dcB; // Iff both are undefined
},
};
};

0 comments on commit 23b32a1

Please sign in to comment.