-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
metadata.ts
67 lines (61 loc) 路 1.47 KB
/
metadata.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { Predicate } from "./is.ts";
import { inspect } from "./inspect.ts";
/**
* A type that has metadata.
*/
export type WithMetadata<T> = {
__unknownutil_metadata: T;
};
/**
* Get typeof the metadata
*/
export type GetMetadata<T> = T extends WithMetadata<infer M> ? M : never;
/**
* Get metadata from the given value
*/
export function getMetadata<T>(v: unknown): T | undefined {
if (v == null) return undefined;
// deno-lint-ignore no-explicit-any
return (v as any).__unknownutil_metadata;
}
/**
* Metadata of a predicate factory function.
*/
export type PredicateFactoryMetadata = {
name: string;
args: unknown[];
};
/**
* Set metadata to a predicate factory function.
*/
export function setPredicateFactoryMetadata<
P extends Predicate<unknown>,
M extends PredicateFactoryMetadata,
>(
pred: P,
metadata: M,
): P & WithMetadata<M> {
let cachedName: string | undefined;
return Object.defineProperties(pred, {
__unknownutil_metadata: {
value: metadata,
configurable: true,
},
name: {
get: () => {
if (cachedName) return cachedName;
const { name, args } = metadata;
cachedName = `${name}(${args.map((v) => inspect(v)).join(", ")})`;
return cachedName;
},
},
}) as P & WithMetadata<M>;
}
/**
* Get metadata from a predicate factory function.
*/
export function getPredicateFactoryMetadata<M extends PredicateFactoryMetadata>(
v: WithMetadata<M>,
): M {
return getMetadata(v) as M;
}