Skip to content

Commit

Permalink
improve map functions to return empty incase the optional is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
manusant committed May 2, 2024
1 parent 8bdde10 commit 9aaf205
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 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.9.7",
"version": "1.9.8",
"description": "Delicious Dish for Typescript and JavaScript projects",
"author": "Manuel Santos <ney.br.santos@gmail.com>",
"license": "MIT",
Expand Down
16 changes: 7 additions & 9 deletions src/optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,17 +322,16 @@ export class Optional<T> {
* @param mapper - A function that takes the current value of type T and returns a new value of type U.
* @param defaultValue - default value when the optional is empty
* @return Returns a new Optional object with the mapped value.
* returns a new Optional object with the mapped value or the default Optional value.
* Throws an error if the original Optional object is empty.
* returns a new Optional object with the mapped value, the default Optional value or empty.
* */
map<U>(mapper: (value: T) => U, defaultValue?: U): Optional<U> {
map<U>(mapper: (value: T) => U, defaultValue?: U): Optional<U | undefined> {
if (this.isPresent()) {
return Optional.of(mapper(this.value!));
}
if (defaultValue) {
return Optional.of(defaultValue);
}
throw new Error("Map operation cannot be called on an empty Optional");
return Optional.empty();
}

/**
Expand All @@ -347,14 +346,13 @@ export class Optional<T> {
*
* @param mapper (function) - A function that takes the value of type T inside the Optional object and returns an
* Optional object with a mapped value of type U.
* @return Returns a new Optional object with the mapped value.
* Throws an error if the original Optional object is empty.
* @return Returns a new Optional object with the mapped value, or empty.
* */
flatMap<U>(mapper: (value: T) => Optional<U>): Optional<U> {
flatMap<U>(mapper: (value: T) => Optional<U>): Optional<U | undefined> {
if (this.isPresent()) {
return mapper(this.value!);
}
throw new Error("FlatMap operation cannot be called on an empty Optional");
return Optional.empty();
}

/**
Expand Down Expand Up @@ -387,7 +385,7 @@ export class Optional<T> {
if (this.isPresent()) {
return mapper(this.value!).then(result => result.isPresent() ? result : Optional.empty());
}
return Promise.reject(new Error("FlatMap operation cannot be called on an empty Optional"));
return Optional.empty();
}

/**
Expand Down

0 comments on commit 9aaf205

Please sign in to comment.