UNPKG

tiny-types

Version:

A tiny library that brings Tiny Types to JavaScript and TypeScript

52 lines 1.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.and = and; const isArray_1 = require("./isArray"); const isDefined_1 = require("./isDefined"); const isGreaterThan_1 = require("./isGreaterThan"); const Predicate_1 = require("./Predicate"); /** * @desc Ensures that the `value` meets all the provided {@link Predicate}s. * * @example * import { and, ensure, isDefined, isGreaterThan, isInteger, TinyType } from 'tiny-types'; * * class AgeInYears extends TinyType { * constructor(public readonly value: number) { * ensure('AgeInYears', value, and(isDefined(), isInteger(), isGreaterThan(18)); * } * } * * @param {...Array<Predicate<T>>} predicates * @returns {Predicate<T>} */ function and(...predicates) { return new And(predicates); } /** @access private */ class And extends Predicate_1.Predicate { predicates; constructor(predicates) { super(); this.predicates = predicates; const results = [ _ => (0, isDefined_1.isDefined)().check(_), _ => (0, isArray_1.isArray)().check(_), _ => (0, isGreaterThan_1.isGreaterThan)(0).check(_.length), ]; if (results.some(check => check(this.predicates) instanceof Predicate_1.Failure)) { throw new Error(`Looks like you haven't specified any predicates to check the value against?`); } } /** @override */ check(value) { for (const predicate of this.predicates) { const result = predicate.check(value); if (result instanceof Predicate_1.Failure) { return result; } } return new Predicate_1.Success(value); } } //# sourceMappingURL=and.js.map