enum.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const codegen_1 = require("../../compile/codegen");
  4. const metadata_1 = require("./metadata");
  5. const def = {
  6. keyword: "enum",
  7. schemaType: "array",
  8. code(cxt) {
  9. metadata_1.checkMetadata(cxt);
  10. const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
  11. if (schema.length === 0)
  12. throw new Error("enum must have non-empty array");
  13. if (schema.length !== new Set(schema).size)
  14. throw new Error("enum items must be unique");
  15. let valid;
  16. if (schema.length >= it.opts.loopEnum) {
  17. if (parentSchema.nullable) {
  18. valid = gen.let("valid", codegen_1._ `${data} === null`);
  19. gen.if(codegen_1.not(valid), loopEnum);
  20. }
  21. else {
  22. valid = gen.let("valid", false);
  23. loopEnum();
  24. }
  25. }
  26. else {
  27. /* istanbul ignore if */
  28. if (!Array.isArray(schema))
  29. throw new Error("ajv implementation error");
  30. valid = codegen_1.or(...schema.map((value) => codegen_1._ `${data} === ${value}`));
  31. if (parentSchema.nullable)
  32. valid = codegen_1.or(codegen_1._ `${data} === null`, valid);
  33. }
  34. cxt.pass(valid);
  35. function loopEnum() {
  36. gen.forOf("v", schemaValue, (v) => gen.if(codegen_1._ `${valid} = ${data} === ${v}`, () => gen.break()));
  37. }
  38. },
  39. };
  40. exports.default = def;
  41. //# sourceMappingURL=enum.js.map