UNPKG

dilswer

Version:

Blazingly fast data validation library with TypeScript integration.

66 lines (64 loc) 2.01 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/data-types/types/tuple.ts import { BaseType } from "../base-type.mjs"; import { getStandardSchemaProps } from "../generate-standard-schema.mjs"; import { ValidationError } from "../../validation-algorithms/validation-error/validation-error.mjs"; var TupleType = class extends BaseType { constructor(tuple) { super(); this.tuple = tuple; __publicField(this, "kind", "tuple"); Object.freeze(this.tuple); Object.freeze(this); } /** @internal */ _acceptVisitor(visitor) { const children = []; for (let i = 0; i < this.tuple.length; i++) { children.push(this.tuple[i]._acceptVisitor(visitor)); } return visitor.visit(this, children); } get ["~standard"]() { return getStandardSchemaProps(this); } ["~validate"](path, value) { if (!Array.isArray(value)) { throw new ValidationError(path, this, value, "not an array"); } if (value.length !== this.tuple.length) { throw new ValidationError( path, this, value, "too many or too few elements in array" ); } for (let index = 0; index < this.tuple.length; index++) { const elem = value[index]; const elemtType = this.tuple[index]; elemtType["~validate"]( path.concat(index), elem ); } } ["~matches"](value) { if (!Array.isArray(value) || value.length !== this.tuple.length) { return false; } for (let index = 0; index < this.tuple.length; index++) { const elem = value[index]; const elemtType = this.tuple[index]; if (!elemtType["~matches"](elem)) { return false; } } return true; } }; export { TupleType };