-
Notifications
You must be signed in to change notification settings - Fork 2
/
struct.ts
31 lines (28 loc) · 1.04 KB
/
struct.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
import { define, StructFactory, TupleFactory } from "../index.ts";
const nameOf = (key: string) =>
/*@__PURE__*/ isNaN(+key) ? /*@__PURE__*/ JSON.stringify(key) : key;
export const struct: StructFactory = (definition) => {
const keys = /*@__PURE__*/ Object.keys(definition);
const indexes = /*@__PURE__*/ Object.keys(keys).map((i) => +i);
const values = /*@__PURE__*/ Object.values(definition);
return /*@__PURE__*/ new Function(
"d",
`[${indexes.map((i) => "k" + i).join()}]`,
`[${indexes.map((i) => "s" + i).join()}]`,
`[${indexes.map((i) => "d" + i).join()}]`,
`return d((c,d)=>{${indexes
.map((i) => `s${i}(c,d[${nameOf(keys[i])}])`)
.join(";")}},(c)=>{const d=${
definition instanceof Array ? "[]" : "{}"
};${indexes
.map((i) => `d[${nameOf(keys[i])}]=d${i}(c)`)
.join(";")};return d})`
)(
define,
keys,
/*@__PURE__*/ values.map(({ ser }) => ser),
/*@__PURE__*/ values.map(({ des }) => des)
);
};
export const tuple: TupleFactory = (...definition) =>
struct(definition);