UNPKG

tiny-types

Version:

A tiny library that brings Tiny Types to JavaScript and TypeScript

109 lines 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Predicate = exports.Failure = exports.Success = exports.Result = void 0; /** * @access public */ class Result { value; constructor(value) { this.value = value; } } exports.Result = Result; /** * @access public */ class Success extends Result { } exports.Success = Success; /** * @access public */ class Failure extends Result { description; constructor(value, description) { super(value); this.description = description; } } exports.Failure = Failure; /** * @desc Describes a {@link Condition} that the `value` should meet. * * To define a custom predicate to be used with the {@link check} function * you can either extend the {@link Predicate}, or use the {@link Predicate.to} factory method. * * @example <caption>Assuming we'd like to create an isDefined() predicate:</caption> * ensure(`some value`, value, isDefined()); * * @example <caption>We can either use the Predicate.to factory method:</caption> * * import { Predicate } from 'tiny-types'; * * function isDefined<T>(): Predicate<T> { * return Predicate.to(`be defined`, (value: T) => * ! (value === null || value === undefined), * ); * } * * @example <caption>or extend the Predicate itself</caption> * * import { Predicate, Result, Success, Failure } from 'tiny-types'; * * function isDefined<T>() { * return new IsDefined<T>(); * } * * class IsDefined<T> extends Predicate<T> { * check(value: T): Result<T> { * return ! (value === null || value === undefined) * ? new Success(value) * : new Failure(value, `be defined`); * } * } * * @access public */ class Predicate { /** * @desc A factory method instantiating a single-condition predicate. * You can use it instead of extending the {Predicate} to save some keystrokes. * * @example * Predicate.to(`be defined`, (value: T) => ! (value === null || value === undefined)); * * @param {string} description - The description of the condition is used by {@link check} to generate the error * message. The description should be similar to`be defined`, * `be less than some value` for the error message to make sense. * @param {Condition<V>} condition - a function that takes a value of type `V` and returns a boolean * indicating whether or not the condition is met. For example: * `(value: V) => !! value` * @returns {Predicate<V>} * * @static */ static to(description, condition) { return new SingleConditionPredicate(description, condition); } } exports.Predicate = Predicate; /** * @access private */ class SingleConditionPredicate extends Predicate { description; isMetBy; constructor(description, isMetBy) { super(); this.description = description; this.isMetBy = isMetBy; } /** @override */ check(value) { return this.isMetBy(value) ? new Success(value) : new Failure(value, this.description); } } //# sourceMappingURL=Predicate.js.map