Optional

Optional gives the power to differentiate between the absence of a value and the null or undefined reference

The Optional class is an utility class that provides a way to handle potentially null or undefined values in a more concise and expressive manner. It allows wrapping a value in an Optional object, which can then be used to perform various operations on the value, such as checking if it is present, retrieving it, applying transformations, and handling empty values.

Overall, this simple yet powerful class helps create code that’s, simply put, more readable and less error-prone than its procedural counterpart.

Global Functions

The best way to wrap and starting using optional is through the global utility functions.

optionalOf

Wraps a value that might be undefined or null in an Optional container.

const result1 = optionalOf("Hello");
if (result1.isPresent()) {
  console.log(result1.get()); // Prints: Hello
}

const result2 = optionalOf(null);
if (result2.isEmpty()) {
  console.log("Value is not present"); // Prints: Value is not present
}

const result3 = optionalOf(undefined);
console.log(result3.orElse("Default")); // Prints: Default

const result4 = await optionalOf(user)
  .orElseThrow(() => new HttpError(409, "User doesn't exist"))
  .map(user => {
    return {
      ...user,
      userData,
    };
  })
  .runAsync(user => this.userRepository.save(user));
console.log(result4); // Prints: saved user content

allPresent

Checks if all the elements in an array of Optional objects have a non-empty value.

anyPresent

Checks if at least one Optional object in an array is present.

nonePresent

Checks if none of the Optional objects in the array are present.

coalesce

Returns the first non-empty optional from a list of optionals, or an empty optional if all optionals are empty.

Class Functions

of

The of method creates a new Optional object with a specified value. It wraps the value, allowing for more concise and expressive code when dealing with potentially null or undefined values.

empty

The empty method returns an empty Optional object.

allPresent

The allPresent method checks if all elements in an array of Optional objects are present.

anyPresent

Checks if at least one Optional object in an array is present.

nonePresent

The nonePresent method checks if none of the Optional objects in the array are present.

coalesce

Returns the first non-empty Optional from a list of optionals, or an empty optional if all optionals are empty.

isPresent

Checks if the value inside the Optional object is present.

ifPresent

Executes a specified action if the value inside the Optional object is present.

ifPresentThrow

Throws an error if the value inside the Optional object is present.

ifThrow

Throws an error based on a predicate if the value inside the Optional object satisfies the predicate.

if

Applies a mapper function if the value inside the Optional object satisfies a predicate.

get

Retrieves the value inside the Optional object or throws an error if empty.

orElse

Retrieves the value inside the Optional object or returns a default value if empty.

orElseGet

Returns the value of the Optional if present; otherwise, invokes the provided supplier function and returns its result.

orElseThrow

Retrieve the value of the Optional object if it is present, or throw an error if the Optional object is empty.

map

Transform the value inside the Optional object using a provided mapper function. It returns a new Optional object with the mapped value. If the original Optional object is empty, it throws an error.

flatMap

Apply a mapper function to the value inside the Optional object and return a new Optional object with the mapped value. If the original Optional object is empty, it throws an error.

flatMapAsync

Chaining asynchronous operations on an optional value. It takes a mapper function that returns a promise of an Optional object. If the current optional value is present, it applies the mapper function and returns the result as an Optional object. If the current optional value is empty, it returns an empty Optional object.

filter

Filter the value inside the Optional object based on a given predicate function. It returns a new Optional object containing the filtered value if the original Optional object is present, or an empty Optional object if the original Optional object is not present.

isEmpty

Checks if the value inside the Optional object is empty or not.

ifEmpty

Executes a specified action if the value inside the Optional object is empty.

ifEmptyThrow

Throws an error if the value inside the Optional object is empty, otherwise it returns the Optional object.

ifEmptyGet

Returns the value inside the Optional object if it is not empty, otherwise it returns a default value provided by a callback function.

contains

Checks if the value inside the Optional object contains a given search value.

every

Checks if a given predicate function returns true for every value inside the Optional object.

some

Checks if a given predicate function returns true for at least one value inside the Optional object.

match

Checks if the value inside the Optional object matches a given condition.

run

Allows you to execute a callback function on the value stored in the Optional object and return a new Optional object with the result.

runAsync

Allows you to asynchronously execute a callback function on the value contained within the Optional object.

else

Used to provide an alternative value or action when the optional value is empty.

elseAsync

Used to execute a callback function asynchronously if the optional value is empty. It returns a promise that resolves to the result of the callback function.

equals

Compares the current Optional object with another Optional object for equality.

Last updated