From 6c477cad7941228057837db1f251b54694e7870a Mon Sep 17 00:00:00 2001 From: manusant Date: Thu, 2 May 2024 19:42:30 +0100 Subject: [PATCH] Add async implementation for if --- package.json | 2 +- src/optional.ts | 25 +++++++++++++++++++------ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index c33e305..73f722f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "katxupa", - "version": "1.10.0", + "version": "1.10.1", "description": "Delicious Dish for Typescript and JavaScript projects", "author": "Manuel Santos ", "license": "MIT", diff --git a/src/optional.ts b/src/optional.ts index 38f9064..cd9ab99 100644 --- a/src/optional.ts +++ b/src/optional.ts @@ -205,7 +205,7 @@ export class Optional { * @param {(value: T) => U} mapper - A function that takes the wrapped value and returns a new value of type U. * @returns {Optional} - An Optional containing the result of applying the mapper function if the predicate * returns true, otherwise returns the current Optional. - * @throws {Error} - Throws an error if called on an empty Optional. + * * @example * const optional = Optional.of(42); * const newOptional = optional.if((value) => value > 10, (value) => value * 2); @@ -215,16 +215,29 @@ export class Optional { * @example * const emptyOptional = Optional.empty(); * emptyOptional.if(() => false, (value) => value * 2); - * // Throws an error since 'if' cannot be called on an empty Optional. + */ if(predicate: (value: T) => boolean, mapper: (value: T) => U): Optional { - this.ifEmptyThrow(() => new Error("'if' can only be called for non empty optionals")); - if (predicate(this.value!)) { - return Optional.of(mapper(this.value!)); + if (!this.isEmpty()) { + if (predicate(this.value!)) { + return Optional.of(mapper(this.value!)); + } + return this; } - return this; + return Optional.empty(); } + async ifAsync(predicate: (value: T) => Promise, mapper: (value: T) => U): Promise> { + if (!this.isEmpty()) { + if (await predicate(this.value!)) { + return Optional.of(mapper(this.value!)); + } + return this; + } + return Optional.empty(); + } + + /** * The get method is used to retrieve the value inside the Optional object. If the Optional * object is empty, it throws an error indicating that the value is not present.