UNPKG

sussy-util

Version:
96 lines (95 loc) 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class Optional { constructor(value) { this.value = value; } /** * Retrieves the value if it's present, otherwise returns undefined. * @returns The value if present, otherwise undefined. */ get() { return this.value; } /** * Checks if the value is present. * @returns True if the value is present, false otherwise. */ isPresent() { return this.value !== void 0; } /** * Retrieves the value if it's present, otherwise returns a specified default value. * @param other The default value to return if the value is absent. * @returns The value if present, otherwise the specified default value. */ orElse(other) { return this.value !== void 0 ? this.value : other; } /** * Maps the value to a new value if present, otherwise returns an empty Optional. * @param mapper A function to transform the value. * @returns An Optional containing the transformed value if present, otherwise an empty Optional. */ map(mapper) { if (this.value !== void 0) { return new Optional(mapper(this.value)); } return Optional.empty(); } /** * Maps the value to a new Optional if present, otherwise returns an empty Optional. * Then applies a function to the value and flattens the result. * @param mapper A function to transform the value and return an Optional. * @returns An Optional containing the transformed value if present, otherwise an empty Optional. */ flatMap(mapper) { if (this.value !== void 0) { return mapper(this.value); } return Optional.empty(); } /** * Applies a function to the value if present, otherwise does nothing. * @param consumer A function to apply to the value if present. */ ifPresent(consumer) { if (this.value !== void 0) { consumer(this.value); } } /** * Filters the value based on a predicate function. * @param predicate A function to test the value. * @returns An Optional containing the value if it passes the predicate, otherwise an empty Optional. */ filter(predicate) { if (this.value !== void 0 && predicate(this.value)) { return new Optional(this.value); } return Optional.empty(); } /** * Returns an empty Optional. * @returns An empty Optional instance. */ static empty() { return this.EMPTY; } /** * Returns a new Optional with a value if it's present, otherwise an empty Optional. * @param value The value to wrap. * @returns An Optional containing the value if not undefined, otherwise an empty Optional. */ static of(value) { return new Optional(value); } static ofNullable(value) { if (value === null || value === void 0) { return Optional.empty(); } return Optional.of(value); } } Optional.EMPTY = new Optional(void 0); exports.default = Optional;