UNPKG

@matatbread/typia

Version:

Superfast runtime validators with only one line

53 lines (50 loc) 1.81 kB
import ts from 'typescript'; /** @internal */ const decode_union_object = (props) => ts.factory.createCallExpression(ts.factory.createArrowFunction(undefined, undefined, [], undefined, undefined, iterate({ escaper: props.escaper, input: props.input, unions: props.objects.map((object) => ({ type: "object", is: () => props.success(props.checker({ input: props.input, explore: props.explore, object, })), value: () => props.decoder({ input: props.input, explore: props.explore, object, }), })), expected: `(${props.objects.map((t) => t.name).join(" | ")})`, })), undefined, undefined); /** @internal */ const iterate = (props) => { const branches = []; for (const u of props.unions) { const condition = u.is(); if (condition.kind === ts.SyntaxKind.TrueKeyword) { branches.push({ condition: null, value: u.value(), }); break; } branches.push({ condition, value: u.value(), }); } if (branches.length === 0) return ts.factory.createBlock([props.escaper(props)], true); else if (branches.length === 1 && branches[0].condition === null) return branches[0].value; const statements = branches.map((b) => b.condition !== null ? ts.factory.createIfStatement(b.condition, ts.factory.createReturnStatement(b.value), undefined) : ts.factory.createReturnStatement(b.value)); if (branches.at(-1).condition !== null) statements.push(props.escaper(props)); return ts.factory.createBlock(statements, true); }; export { decode_union_object }; //# sourceMappingURL=decode_union_object.mjs.map