Skip to content

Commit

Permalink
cellify: revert to v.constructor.prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
hbbio committed Feb 5, 2024
1 parent ad40b02 commit 3454f64
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions src/cellify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ export type Cellified<T> = T extends object
: ValueCell<T>;

// Uncellified computes an uncellified type.
export type Uncellified<T> = T extends AnyCell<infer U>
? U extends object
? U extends Array<infer Elt>
? Array<Uncellified<Elt>>
: {
[P in keyof U]: Uncellified<U[P]>;
}
: U
: T;
export type Uncellified<T> =
T extends AnyCell<infer U>
? U extends object
? U extends Array<infer Elt>
? Array<Uncellified<Elt>>
: {
[P in keyof U]: Uncellified<U[P]>;
}
: U
: T;

/**
* cellify converts any value to a Cellified value where each array or record
Expand All @@ -29,20 +30,22 @@ export type Uncellified<T> = T extends AnyCell<infer U>
* @returns
* @todo cell reuses
*/
export const _cellify = <T>(proxy: SheetProxy, v: T): Cellified<T> => {
export const _cellify = <T,>(proxy: SheetProxy, v: T): Cellified<T> => {
if (v instanceof Cell) throw new Error("cell");
return proxy.new(
Array.isArray(v)
? v.map((vv) => _cellify(proxy, vv), "cellify.[]")
: typeof v === "object" && v !== null && v.constructor?.name === "Object" // exclude classes
: typeof v === "object" &&
v !== null &&
v.constructor.prototype === Object.prototype // exclude classes
? Object.fromEntries(
Object.entries(v).map(
([k, vv]) => [k, _cellify(proxy, vv)],
"cellify.{}"
)
"cellify.{}",
),
)
: v,
"cellify"
"cellify",
) as Cellified<T>;
};

Expand All @@ -51,24 +54,24 @@ export const _cellify = <T>(proxy: SheetProxy, v: T): Cellified<T> => {
* @param v any value
* @returns value without cells
*/
export const _uncellify = async <T>(
v: T | AnyCell<T>
export const _uncellify = async <T,>(
v: T | AnyCell<T>,
): Promise<Uncellified<T>> => {
const value = v instanceof Cell ? await v.get() : v;
if (value instanceof Error) throw value;
if (Array.isArray(value))
return Promise.all(
value.map(async (_element) => await _uncellify(_element))
value.map(async (_element) => await _uncellify(_element)),
) as Promise<Uncellified<T>>;
if (
typeof value === "object" &&
value !== null &&
value.constructor?.name === "Object" // exclude classes
value.constructor.prototype === Object.prototype // exclude classes
)
return Object.fromEntries(
await Promise.all(
Object.entries(value).map(async ([k, vv]) => [k, await _uncellify(vv)])
)
Object.entries(value).map(async ([k, vv]) => [k, await _uncellify(vv)]),
),
);
// Classes, null or base types (string, number, ...)
return value as Uncellified<T>;
Expand Down

0 comments on commit 3454f64

Please sign in to comment.