Class Optional<T>

The Optional class is a 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.

Since

version 1.0.2

Author

Manuel Santos ney.br.santos@gmail.com

Type Parameters

  • T

Constructors

Properties

value: undefined | null | T

Methods

  • The contains method checks if the value inside the Optional object contains a given search value.

    Parameters

    • searchValue: T

      (generic type) - The value to search for in the Optional object.

    Returns boolean

    boolean: Returns true if the value inside the Optional object contains the search value, otherwise returns false.

    Example

    const optional = Optional.of([1, 2, 3, 4, 5]);
    const searchValue = 3;
    const result = optional.contains(searchValue);
    console.log(result); // true
  • The convert method is used to convert the value inside the Optional object to a different type using a provided converter function.

    Type Parameters

    • U

    Parameters

    • converter: ((value) => U)

      A function that takes the current value of type T inside the Optional object and returns a value of type U.

        • (value): U
        • Parameters

          • value: T

          Returns U

    Returns Optional<undefined | U>

    Returns a new Optional object containing the converted value if the original Optional object is present. Returns an empty Optional object if the original Optional object is not present.

  • The else method in the Optional class is used to provide an alternative value or action when the optional value is empty.

    Type Parameters

    • R

    Parameters

    • callback: (() => R)

      A function that returns a value of type R. This function is executed when the optional value is empty.

        • (): R
        • Returns R

    Returns Optional<R>

    An Optional object that contains the alternative value returned by the callback function, if the optional value is empty.

  • The elseAsync method in the Optional class is 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.

    Type Parameters

    • R

    Parameters

    • callback: (() => Promise<R>)

      A function that returns a promise. This function will be executed if the optional value is empty.

        • (): Promise<R>
        • Returns Promise<R>

    Returns Promise<R>

    A promise that resolves to the result of the callback function if the optional value is empty.

    Example

    const optionalValue: Optional<number> = Optional.of(5);
    const result = await optionalValue.elseAsync(() => Promise.resolve(10));
    console.log(result); // Output: 5

    const emptyOptional: Optional<number> = Optional.empty();
    const alternativeResult = await emptyOptional.elseAsync(() => Promise.resolve(10));
    console.log(alternativeResult); // Output: 10
  • Compares the current Optional with another Optional for equality.

    Type Parameters

    • U

    Parameters

    • other: Optional<U>

      The Optional to compare with.

    Returns boolean

    true if the two Optionals are equal, false otherwise.

    Example

    const optional1 = Optional.of(42);
    const optional2 = Optional.of(42);
    const optional3 = Optional.of(99);

    console.log(optional1.equals(optional2)); // true (both contain the same value)
    console.log(optional1.equals(optional3)); // false (contain different values)
    console.log(optional1.equals(Optional.empty())); // false (one is non-empty, the other is empty)
    console.log(Optional.empty().equals(Optional.empty())); // true (both are empty)
  • The every method checks if a given predicate function returns true for every value inside the Optional object.

    Example Usage

    const optional = Optional.of([1, 2, 3]);
    const result = optional.every(value => value > 0);
    console.log(result); // true

    Parameters

    • predicate: ((value) => boolean)

      (function) - A predicate function that takes a value of type T and returns a boolean value.

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns boolean

    Returns true if the predicate function returns true for every value inside the Optional object. Returns false if the Optional object is empty or if the predicate function returns false for any value.

  • The filter method is used to 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.

    Parameters

    • predicate: ((value) => boolean)

      (function) - A predicate function that takes a value of type T and returns a boolean value indicating whether the value should be included in the filtered result or not.

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns Optional<undefined | T>

    Returns a new Optional object containing the filtered value if the original Optional object is present. Returns an empty Optional object if the original Optional object is not present.

    Example

    const optional = Optional.of([1, 2, 3, 4, 5]); // Create an Optional object with an array value
    const filteredOptional = optional.filter(value => value > 3); // Filter the array to keep only values greater than 3
    console.log(filteredOptional.get()); // Output: [4, 5]

    const emptyOptional = Optional.empty(); // Create an empty Optional object
    const filteredEmptyOptional = emptyOptional.filter(value => value > 3); // Filter the empty Optional object
    console.log(filteredEmptyOptional.isEmpty()); // Output: true
  • The flatMap method is used to 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.

    Type Parameters

    • U

    Parameters

    • mapper: ((value) => Optional<U>)

      (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.

    Returns Optional<U>

    Returns a new Optional object with the mapped value. Throws an error if the original Optional object is empty.

    Example

    const optional = Optional.of(5);
    const mappedOptional = optional.flatMap(value => Optional.of(value * 2));
    console.log(mappedOptional.get()); // Output: 10
  • The flatMapAsync method allows for chaining asynchronous operations on an optional value. It takes a mapper function that returns a promise of an Optional object, and if the current optional value is present, it applies the mapper function and returns the result. If the current optional value is empty, it returns an empty Optional object.

    Type Parameters

    • U

    Parameters

    • mapper: ((value) => Promise<Optional<U>>)

      A function that takes the current value of the optional and returns a promise of an Optional object.

    Returns Promise<Optional<undefined | null | U>>

    An Optional object that contains the result of the mapper function, or an empty Optional object if the current optional value is empty

    Example

    const optionalValue = Optional.of(5);
    const asyncMapper = (value: number) => {
    return new Promise<Optional<number>>((resolve) => {
    setTimeout(() => {
    resolve(Optional.of(value * 2));
    }, 1000);
    });
    };

    optionalValue.flatMapAsync(asyncMapper)
    .then((result) => {
    console.log(result.get()); // Output: 10
    })
    .catch((error) => {
    console.error(error);
    });
  • 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.

    Returns T

    The value inside the Optional object if it is present. Throws an error with the message "Value is not present" if the Optional object is empty.

  • Applies a predicate function to the wrapped value and returns an Optional containing the result of applying the mapper function if the predicate returns true, otherwise returns the current Optional.

    Type Parameters

    • U

      The type of the value returned by the mapper function.

    Parameters

    • predicate: ((value) => boolean)

      A function that takes the wrapped value and returns a boolean. If true, the mapper function will be applied.

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    • mapper: ((value) => U)

      A function that takes the wrapped value and returns a new value of type U.

        • (value): U
        • Parameters

          • value: T

          Returns U

    Returns Optional<T | U>

    • An Optional containing the result of applying the mapper function if the predicate returns true, otherwise returns the current Optional.

    Throws

    • 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);
    // If the wrapped value is greater than 10, returns an Optional containing the result of doubling the value.
    // Otherwise, returns the original Optional.

    Example

    const emptyOptional = Optional.empty();
    emptyOptional.if(() => false, (value) => value * 2);
    // Throws an error since 'if' cannot be called on an empty Optional.
  • The ifEmpty method executes a specified action if the value inside the Optional object is empty.

    Parameters

    • action: (() => void)

      A callback function that performs an action when the value inside the Optional object is empty.

        • (): void
        • Returns void

    Returns Optional<T>

    Returns the Optional object itself.

    Example

    const optional = Optional.of(null);
    optional.ifEmpty(() => console.log("Value is empty")); // Output: "Value is empty"
  • The ifEmptyGet method returns the value inside the Optional object if it is not empty, otherwise it returns a default value provided by a callback function.

    Parameters

    • defaultValueProvider: (() => T)

      A callback function that returns a default value of type T.

        • (): T
        • Returns T

    Returns T

    Returns the value inside the Optional object if it is not empty or the default value provided by the defaultValueProvider callback function if the Optional object is empty.

    Example

    const optional = Optional.of("Hello");
    const result = optional.ifEmptyGet(() => "Default Value");
    console.log(result); // Output: "Hello"

    const emptyOptional = Optional.empty();
    const defaultValue = emptyOptional.ifEmptyGet(() => "Default Value");
    console.log(defaultValue); // Output: "Default Value"
  • The ifEmptyThrow method throws an error if the value inside the Optional object is empty, otherwise it returns optional.

    Parameters

    • errorProvider: (() => Error)

      A callback function that returns an Error object.

        • (): Error
        • Returns Error

    Returns Optional<T>

    Returns the Optional object if it is not empty or Throws an error if the Optional object is empty.

    Example

    const optional = Optional.of("value");
    optional.ifEmptyThrow(() => new Error("Value is empty")); // Returns the optional object

    const emptyOptional = Optional.empty();
    emptyOptional.ifEmptyThrow(() => new Error("Value is empty")); // Throws an error
  • T he ifPresent method is used to execute a specified action if the value inside the Optional object is present.

    Parameters

    • consumer: ((value) => void)

      (function) - A callback function that takes the value of type T inside the Optional object and performs an action.

        • (value): void
        • Parameters

          • value: T

          Returns void

    Returns void

  • The ifPresentThrow method in the Optional class checks if a value is present and throws an error if it is. It then returns Optional.

    Parameters

    • errorProvider: (() => Error)

      A function that returns an Error object.

        • (): Error
        • Returns Error

    Returns Optional<T>

    The Optional if not present.

  • Executes a provided predicate function on the wrapped value and throws an error if the predicate returns true.

    Parameters

    • predicate: ((value) => boolean)

      A function that takes the wrapped value and returns a boolean. If true, an error will be thrown.

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    • errorProvider: (() => Error)

      A function that provides the error to be thrown if the predicate is true.

        • (): Error
        • Returns Error

    Returns Optional<T>

    • The current Optional instance.

    Throws

    • Throws an error provided by the errorProvider if the predicate is true.

    Throws

    • Throws an error if called on an empty Optional.

    Example

    const optional = Optional.of(42);
    optional.ifThrow((value) => value < 0, () => new Error("Value must be non-negative"));
    // If the wrapped value is negative, it throws an error with the specified message.

    Example

    const emptyOptional = Optional.empty();
    emptyOptional.ifThrow(() => false, () => new Error("This will not be executed"));
    // Throws an error since ifThrow cannot be called on an empty Optional.
  • The isEmpty method checks if the value inside the Optional object is empty or not.

    Returns boolean

    A boolean value indicating whether the value inside the Optional object is empty or not. true if the value is empty, false otherwise.

    Example

    const optionalValue = Optional.of("Hello"); // Create an Optional object with a non-empty value
    console.log(optionalValue.isEmpty()); // Output: false

    const emptyOptional = Optional.empty(); // Create an Optional object with an empty value
    console.log(emptyOptional.isEmpty()); // Output: true
  • The isPresent method is used to check if the value inside the Optional object is present or not.

    Returns boolean

    a boolean value indicating whether the value inside the Optional object is present (true) or not (false).

  • The map method is used to transform the value inside the Optional object using a provided mapper function, or return a default value if the Optional is empty.

    Type Parameters

    • U

    Parameters

    • mapper: ((value) => U)

      A function that takes the current value of type T and returns a new value of type U.

        • (value): U
        • Parameters

          • value: T

          Returns U

    • Optional defaultValue: U

      default value when the optional is empty

    Returns Optional<U>

    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.

    Example

    const optional = Optional.of(5); // Create an Optional object with a value of 5
    const mappedOptional = optional.map(value => value * 2); // Map the value to its double
    console.log(mappedOptional.get()); // Output: 10

    const emptyOptional = Optional.empty(); // Create an empty Optional object
    const defaultValue = 0;
    const mappedEmptyOptional = emptyOptional.map(value => value * 2, defaultValue); // Map the value to its double or use the default value if empty
    console.log(mappedEmptyOptional.get()); // Output: 0
  • The match method checks if the value inside the Optional object matches a given condition.

    Parameters

    • condition: RegExp | ((value) => boolean)

      (function or RegExp): The condition to check against the value inside the Optional object. @returnboolean: Returns true if the value inside the Optional object matches the given condition, otherwise returns false.

    Returns boolean

    Example

    const optional = Optional.of(5);
    const isEven = optional.match(value => value % 2 === 0);
    console.log(isEven); // true
  • The orElse method is used to retrieve the value inside the Optional object if it is present, or return a default value if the Optional object is empty.

    Type Parameters

    • R

    Parameters

    • defaultValue: R

      (generic type) - The default value to return if the Optional object is empty.

    Returns T | R

    The value inside the Optional object if it is present. The defaultValue if the Optional object is empty.

  • The orElseGet method is used to retrieve the value inside the Optional object if it is present, or get a default value from a callback function if the Optional object is empty.

    Type Parameters

    • R

    Parameters

    • defaultValueProvider: (() => R)

      (function) - A callback function that returns a default value of type T.

        • (): R
        • Returns R

    Returns T | R

    The value inside the Optional object if it is present. The default value provided by the defaultValueProvider callback function if the Optional object is empty.

    Example

    const optional = Optional.of("Hello");
    const result = optional.orElseGet(() => "Default Value");
    console.log(result); // Output: "Hello"

    const emptyOptional = Optional.empty();
    const defaultValue = emptyOptional.orElseGet(() => "Default Value");
    console.log(defaultValue); // Output: "Default Value"
  • The orElseThrow method is used to retrieve the Optional object if it is present, or throw an error if the Optional object is empty.

    Parameters

    • errorProvider: (() => Error)

      (function) - A callback function that returns an Error object

        • (): Error
        • Returns Error

    Returns Optional<T>

    The Optional object if it is not empty. Throws an error if the Optional object is empty.

    Example

    const optionalValue = Optional.of("Hello");
    const value = optionalValue.orElseThrow(() => new Error("Value is not present"));
    console.log(value); // Output: "Hello"

    const emptyOptional = Optional.empty();
    emptyOptional.orElseThrow(() => new Error("Value is not present")); // Throws an error
  • The run method in the Optional class allows you to execute a callback function on the value stored in the Optional object and return a new Optional object with the result.

    Type Parameters

    • R

    Parameters

    • callback: ((value) => R)

      A function that takes the value stored in the Optional object as an argument and returns a result of type R.

        • (value): R
        • Parameters

          • value: T

          Returns R

    Returns Optional<R>

    Returns a new Optional object that contains the result of executing the callback function on the value stored in the original Optional object.

    Example

    const optional = Optional.of(5); // Create an Optional object with a value of 5
    const newOptional = optional.run(value => value * 2); // Execute the callback function on the value and create a new Optional object with the result
    console.log(newOptional.get()); // Output: 10
  • The runAsync method in the Optional class allows you to asynchronously execute a callback function on the value contained within the Optional object.

    Type Parameters

    • R

    Parameters

    • callback: ((value) => Promise<R>)

      A callback function that takes the value of type T and returns a Promise of type R. This function represents the asynchronous operation to be performed on the value.

        • (value): Promise<R>
        • Parameters

          • value: T

          Returns Promise<R>

    Returns Promise<R>

    A Promise that resolves to the result of the asynchronous operation performed by the callback function.

    Example

    const optional = Optional.of(5); // Create an Optional object with a value of 5

    const asyncCallback = async (value: number) => {
    // Perform some asynchronous operation on the value
    const result = await someAsyncFunction(value);
    return result;
    };

    const resultPromise = optional.runAsync(asyncCallback); // Execute the async callback on the value

    resultPromise.then(result => {
    console.log(result); // Output the result of the asynchronous operation
    }).catch(error => {
    console.error(error); // Handle any errors that occurred during the asynchronous operation
    });
  • The some method checks if a given predicate function returns true for at least one value inside the Optional object.

    Example Usage

    const optional = Optional.of([1, 2, 3]);
    const result = optional.some(value => value > 0);
    console.log(result); // true

    Parameters

    • predicate: ((value) => boolean)

      (function) - A predicate function that takes a value of type T and returns a boolean value.

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns boolean

    Returns true if the predicate function returns true for at least one value inside the Optional object. Returns false if the Optional object is empty or if the predicate function returns false for all values.

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

    Example Usage

    onst optional1 = Optional.of(5);
    const optional2 = Optional.of(10);
    const optional3 = Optional.empty();

    const optionals = [optional1, optional2, optional3];

    const result = Optional.allPresent(optionals);
    console.log(result); // Output: false

    Type Parameters

    • T

    Parameters

    • optionals: Optional<T>[]

      An array of Optional objects.

    Returns boolean

    true if all the Optional objects in the array have a non-empty value. false if any of the Optional objects in the array have an empty value.

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

    Type Parameters

    • T

    Parameters

    • optionals: Optional<T>[]

      An array of Optional objects.

    Returns boolean

    Returns true if at least one Optional object in the array is present, false otherwise.

    Example

    // Example Usage:
    const optional1 = Optional.of(5);
    const optional2 = Optional.empty();
    const optional3 = Optional.of(10);

    const optionals = [optional1, optional2, optional3];

    const result = Optional.anyPresent(optionals);
    console.log(result); // true
  • The coalesce method returns the first non-empty optional from a list of optionals, or an empty optional if all optionals are empty.

    Example Usage

        const optional1 = Optional.of(5);
    const optional2 = Optional.empty();
    const optional3 = Optional.of(10);

    const result = Optional.coalesce(optional1, optional2, optional3);
    console.log(result.get()); // Output: 5

    Type Parameters

    • T

    Parameters

    • Rest ...optionals: Optional<undefined | null | T>[]

      A spread parameter that accepts a variable number of Optional objects

    Returns Optional<undefined | null | T>

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

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

    Type Parameters

    • T

    Parameters

    • optionals: Optional<T>[]

      An array of Optional objects.

    Returns boolean

    Returns true if none of the Optional objects in the array are present, otherwise returns false.

    Example

    // Example 1: All Optionals have values
    const optionalsWithValues = [Optional.of("Hello"), Optional.of("World")];
    const areNonePresent1 = Optional.nonePresent(optionalsWithValues);
    console.log(areNonePresent1); // false (both Optionals have values)

    Example

    // Example 2: All Optionals are empty
    const optionalsWithEmptyValues = [Optional.empty(), Optional.empty()];
    const areNonePresent2 = Optional.nonePresent(optionalsWithEmptyValues);
    console.log(areNonePresent2); // true (both Optionals are empty)

    Example

    // Example 3: At least one Optional has a value
    const mixedOptionals = [Optional.of("Hello"), Optional.empty()];
    const areNonePresent3 = Optional.nonePresent(mixedOptionals);
    console.log(areNonePresent3); // false (at least one Optional has a value)
  • The of method is a static method that creates a new Optional object with a specified value. It is used to wrap a value in an Optional object, allowing for more concise and expressive code when dealing with potentially null or undefined values

    Type Parameters

    • T

    Parameters

    • value: undefined | null | T

      (generic type) - The value to be wrapped in the Optional object. It can be of any type, including undefined or null.

    Returns Optional<T>

    a new Optional object containing the specified value.

Generated using TypeDoc