Private
constructorPrivate
Readonly
valueThe contains method checks if the value inside the Optional object contains a given search value.
(generic type) - The value to search for in the Optional object.
boolean: Returns true if the value inside the Optional object contains the search value, otherwise returns false.
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.
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.
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.
A promise that resolves to the result of the callback function if the optional value is empty.
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.
true if the two Optionals are equal, false otherwise.
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.
const optional = Optional.of([1, 2, 3]);
const result = optional.every(value => value > 0);
console.log(result); // true
(function) - A predicate function that takes a value of type T and returns a boolean value.
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.
(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.
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.
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.
Returns a new Optional object with the mapped value. Throws an error if the original Optional object is empty.
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.
An Optional object that contains the result of the mapper function, or an empty Optional object if the current optional value is empty
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.
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.
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.
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.
A callback function that performs an action when the value inside the Optional object is empty.
Returns the Optional object itself.
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.
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.
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.
A callback function that returns an Error object.
Returns the Optional object if it is not empty or Throws an error if the Optional object is empty.
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.
(function) - A callback function that takes the value of type T inside the Optional object and performs an action.
The ifPresentThrow method in the Optional class checks if a value is present and throws an error if it is. It then returns Optional.
A function that returns an Error object.
The Optional if not present.
Executes a provided predicate function on the wrapped value and throws an error if the predicate returns true.
A function that takes the wrapped value and returns a boolean. If true, an error will be thrown.
A function that provides the error to be thrown if the predicate is true.
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.
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.
A boolean value indicating whether the value inside the Optional object is empty or not. true if the value is empty, false otherwise.
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 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.
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.
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.
(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.
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.
(generic type) - The default value to return if the Optional object is empty.
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.
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.
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.
(function) - A callback function that returns an Error object
The Optional object if it is not empty. Throws an error if the Optional object is empty.
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.
Returns a new Optional object that contains the result of executing the callback function on the value stored in the original Optional object.
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.
A Promise that resolves to the result of the asynchronous operation performed by the callback function.
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.
const optional = Optional.of([1, 2, 3]);
const result = optional.some(value => value > 0);
console.log(result); // true
(function) - A predicate function that takes a value of type T and returns a boolean value.
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.
Static
allThe allPresent method checks if all the elements in an array of Optional objects are present.
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
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.
Static
anyChecks if at least one Optional object in an array is present.
Returns true if at least one Optional object in the array is present, false otherwise.
// 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
Static
coalesceThe coalesce method returns the first non-empty optional from a list of optionals, or an empty optional if all optionals are empty.
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
Returns the first non-empty optional from the list of optionals, or an empty optional if all optionals are empty.
Static
emptyStatic
noneThe nonePresent method checks if none of the Optional objects in the array are present.
Returns true if none of the Optional objects in the array are present, otherwise returns false.
// 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 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 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)
Static
ofThe 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
(generic type) - The value to be wrapped in the Optional object. It can be of any type, including undefined or null.
a new Optional object containing the specified value.
Generated using TypeDoc
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