discriminatedUnion.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const benchmark_1 = __importDefault(require("benchmark"));
  7. const index_1 = require("../index");
  8. const doubleSuite = new benchmark_1.default.Suite("z.discriminatedUnion: double");
  9. const manySuite = new benchmark_1.default.Suite("z.discriminatedUnion: many");
  10. const aSchema = index_1.z.object({
  11. type: index_1.z.literal("a"),
  12. });
  13. const objA = {
  14. type: "a",
  15. };
  16. const bSchema = index_1.z.object({
  17. type: index_1.z.literal("b"),
  18. });
  19. const objB = {
  20. type: "b",
  21. };
  22. const cSchema = index_1.z.object({
  23. type: index_1.z.literal("c"),
  24. });
  25. const objC = {
  26. type: "c",
  27. };
  28. const dSchema = index_1.z.object({
  29. type: index_1.z.literal("d"),
  30. });
  31. const double = index_1.z.discriminatedUnion("type", [aSchema, bSchema]);
  32. const many = index_1.z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]);
  33. doubleSuite
  34. .add("valid: a", () => {
  35. double.parse(objA);
  36. })
  37. .add("valid: b", () => {
  38. double.parse(objB);
  39. })
  40. .add("invalid: null", () => {
  41. try {
  42. double.parse(null);
  43. }
  44. catch (err) { }
  45. })
  46. .add("invalid: wrong shape", () => {
  47. try {
  48. double.parse(objC);
  49. }
  50. catch (err) { }
  51. })
  52. .on("cycle", (e) => {
  53. console.log(`${doubleSuite.name}: ${e.target}`);
  54. });
  55. manySuite
  56. .add("valid: a", () => {
  57. many.parse(objA);
  58. })
  59. .add("valid: c", () => {
  60. many.parse(objC);
  61. })
  62. .add("invalid: null", () => {
  63. try {
  64. many.parse(null);
  65. }
  66. catch (err) { }
  67. })
  68. .add("invalid: wrong shape", () => {
  69. try {
  70. many.parse({ type: "unknown" });
  71. }
  72. catch (err) { }
  73. })
  74. .on("cycle", (e) => {
  75. console.log(`${manySuite.name}: ${e.target}`);
  76. });
  77. exports.default = {
  78. suites: [doubleSuite, manySuite],
  79. };