Skip to content

Commit

Permalink
Add async implementation for if
Browse files Browse the repository at this point in the history
  • Loading branch information
manusant committed May 2, 2024
1 parent db5f37d commit 6c477ca
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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 <ney.br.santos@gmail.com>",
"license": "MIT",
Expand Down
25 changes: 19 additions & 6 deletions src/optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export class Optional<T> {
* @param {(value: T) => U} mapper - A function that takes the wrapped value and returns a new value of type U.
* @returns {Optional<U | T>} - 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);
Expand All @@ -215,16 +215,29 @@ export class Optional<T> {
* @example
* const emptyOptional = Optional.empty();
* emptyOptional.if(() => false, (value) => value * 2);
* // Throws an error since 'if' cannot be called on an empty Optional.
*/
if<U>(predicate: (value: T) => boolean, mapper: (value: T) => U): Optional<U | T> {
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<U>(predicate: (value: T) => Promise<boolean>, mapper: (value: T) => U): Promise<Optional<U | T>> {
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.
Expand Down

0 comments on commit 6c477ca

Please sign in to comment.