Skip to content

Commit

Permalink
copy: new utility function to copy any Cell as ValueCell
Browse files Browse the repository at this point in the history
  • Loading branch information
hbbio committed Apr 17, 2024
1 parent 7c5b0cd commit b04bd1a
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/copy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { expect, test } from "vitest";

import { copy } from "./copy";
import { delayed } from "./promise";
import { SheetProxy } from "./proxy";
import { Sheet } from "./sheet";

test("copy cell", async () => {
const sheet = new Sheet();
const proxy = new SheetProxy(sheet);

const a = proxy.new("foo");
const b = a.map((s) => s.length);
const c = copy(proxy, b);

await expect(c.get()).resolves.toBe(3);
});

test("copy cell async", async () => {
const sheet = new Sheet();
const proxy = new SheetProxy(sheet);

const a = proxy.new("foo");
const b = a.map((s) => delayed(s.length, 10));
const c = copy(proxy, b);

await expect(c.get()).resolves.toBe(3);
});

test("copy cell error", async () => {
const sheet = new Sheet();
const proxy = new SheetProxy(sheet);

const err = new Error("error");

const a = proxy.new("foo");
const b = a.map((_s) => {
throw err;
});
const c = copy(proxy, b);
await expect(c.get()).resolves.toBe(err);
});
16 changes: 16 additions & 0 deletions src/copy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { AnyCell, ValueCell } from "./cell";
import type { SheetProxy } from "./proxy";

// Copy any Cell as a ValueCell.
export const copy = <T>(
proxy: SheetProxy,
cell: AnyCell<T>,
name = `copy:${cell.id}`
): ValueCell<T> => {
return proxy.new(
new Promise((resolve, reject) => {
cell.get().then((v) => (v instanceof Error ? reject(v) : resolve(v)));
}),
name
);
};
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export {
type Uncellified
} from "./cellify";
export { clock, clockWork, type Clock } from "./clock";
export { copy } from "./copy";
export { Debugger } from "./debug";
export { jsonStringify } from "./json";
export { nextSubscriber } from "./next";
Expand Down
1 change: 1 addition & 0 deletions src/isEqual.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { expect, test } from "vitest";
* @param b
* @returns
*/
// biome-ignore lint/suspicious/noExportsInTest: used in tests only
export function isEqual<T>(a: T, b: T): boolean {
// Same instance or primitive values are equal
if (a === b) return true;
Expand Down

0 comments on commit b04bd1a

Please sign in to comment.