Skip to content

Commit

Permalink
object: cellifyObject
Browse files Browse the repository at this point in the history
  • Loading branch information
hbbio committed Mar 15, 2024
1 parent a2cc59a commit 3d48eab
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test } from "vitest";

import { _cellify, _uncellify } from "./cellify";
import { mapObject, reduceObject } from "./object";
import { cellifyObject, mapObject, reduceObject } from "./object";
import { SheetProxy } from "./proxy";
import { Sheet } from "./sheet";

Expand Down Expand Up @@ -66,3 +66,19 @@ test("reduceObject", async () => {
await expect(v.get()).resolves.toBe(14);
expect(sheet.stats).toEqual({ count: 8, size: 7 }); // +1 cell, update pointer
});

test("cellifyObject", async () => {
const sheet = new Sheet();
const proxy = new SheetProxy(sheet);
const obj = proxy.new({ a: 1, b: 2, c: 3 } as Record<string, number>);
const c = cellifyObject(proxy, obj);
await expect(_uncellify(c)).resolves.toEqual({ a: 1, b: 2, c: 3 });
expect(sheet.stats).toEqual({ count: 5, size: 5 }); // 1 obj + 3 ç + 1 map
expect(sheet.get(2).value).toBe(1);

obj.set({ a: 4, b: 2, d: 10 });
await expect(_uncellify(c)).resolves.toEqual({ a: 4, b: 2, d: 10 });
expect(sheet.stats).toEqual({ count: 6, size: 6 }); // +1 ç
expect(sheet.get(2).value).toBe(4); // cell has been updated
expect(sheet.get(5).value).toBe(10); // last created is 10
});
27 changes: 26 additions & 1 deletion src/object.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AnyCell, MapCell } from "./cell";
import type { AnyCell, MapCell, ValueCell } from "./cell";
import { collector } from "./gc";
import type { SheetProxy } from "./proxy";

Expand Down Expand Up @@ -75,3 +75,28 @@ export const reduceObject = <
nf
);
};

export const cellifyObject = (
proxy: SheetProxy,
obj: AnyCell<Record<string, unknown>>,
name = "çObj"
): MapCell<CellObject, true> => {
const set = <T>(c: ValueCell<T>, v: T): ValueCell<T> => {
c.set(v);
return c;
};
return proxy.map(
[obj],

Check failure on line 89 in src/object.ts

View workflow job for this annotation

GitHub Actions / test (20.x)

No overload matches this call.
(_obj, prev) => {
// @todo delete unused cells
return Object.fromEntries(
Object.entries(_obj).map(([k, v]) => [
k,
prev?.[k] ? set(prev[k], v) : proxy.new(v)
])
);
},
name,
true
);
};

0 comments on commit 3d48eab

Please sign in to comment.