Skip to content

Commit

Permalink
✅ test: Objects can be converted to YMaps
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jul 9, 2021
1 parent 5dde179 commit e28fd53
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/utility.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Y from "yjs";
import { arrayToYArray, yArrayToArray, } from "./utility";
import { arrayToYArray, objectToYMap, yArrayToArray, } from "./utility";

describe("arrayToYArray", () =>
{
Expand Down Expand Up @@ -104,3 +104,26 @@ describe("arrayToYArray and yArrayToArray are inverses", () =>
expect(yArrayToArray(ymap.get("array"))).toEqual(array);
});
});

describe("objectToYMap", () =>
{
it("Converts an empty object into an empty YMap.", () =>
{
const ydoc = new Y.Doc();
const ymap = ydoc.getMap("tmp");

ymap.set("map", objectToYMap({}));

expect(ymap.get("map").toJSON()).toEqual({});
});

it("Converts an non-empty object into a YMap with the same entries.", () =>
{
const ydoc = new Y.Doc();
const ymap = ydoc.getMap("tmp");

ymap.set("map", objectToYMap({ "foo": 1, }));

expect(ymap.get("map").toJSON()).toEqual({ "foo": 1, });
});
});
14 changes: 13 additions & 1 deletion src/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,16 @@ export const arrayToYArray = (array: any[]): Y.Array<any> =>
};

export const yArrayToArray = (yarray: Y.Array<any>): any[] =>
yarray.toJSON();
yarray.toJSON();

export const objectToYMap = (object: any): Y.Map<any> =>
{
const ymap = new Y.Map();

Object.entries(object).forEach(([ property, value ]) =>
{
ymap.set(property, value);
});

return ymap;
};

0 comments on commit e28fd53

Please sign in to comment.