enum.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const codegen_1 = require("../../compile/codegen");
  4. const util_1 = require("../../compile/util");
  5. const equal_1 = require("../../runtime/equal");
  6. const error = {
  7. message: "must be equal to one of the allowed values",
  8. params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
  9. };
  10. const def = {
  11. keyword: "enum",
  12. schemaType: "array",
  13. $data: true,
  14. error,
  15. code(cxt) {
  16. const { gen, data, $data, schema, schemaCode, it } = cxt;
  17. if (!$data && schema.length === 0)
  18. throw new Error("enum must have non-empty array");
  19. const useLoop = schema.length >= it.opts.loopEnum;
  20. let eql;
  21. const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
  22. let valid;
  23. if (useLoop || $data) {
  24. valid = gen.let("valid");
  25. cxt.block$data(valid, loopEnum);
  26. }
  27. else {
  28. /* istanbul ignore if */
  29. if (!Array.isArray(schema))
  30. throw new Error("ajv implementation error");
  31. const vSchema = gen.const("vSchema", schemaCode);
  32. valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
  33. }
  34. cxt.pass(valid);
  35. function loopEnum() {
  36. gen.assign(valid, false);
  37. gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
  38. }
  39. function equalCode(vSchema, i) {
  40. const sch = schema[i];
  41. return typeof sch === "object" && sch !== null
  42. ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
  43. : (0, codegen_1._) `${data} === ${sch}`;
  44. }
  45. },
  46. };
  47. exports.default = def;
  48. //# sourceMappingURL=enum.js.map