executeIfAs<T> function

T executeIfAs<T>(
  1. bool condition(), {
  2. required T ifTrue(),
  3. required T ifFalse(),
})

Executes one of two functions based on a condition and returns a value of type T.

This function takes a condition function that returns a boolean, and two other functions that return a value of type T. If the condition function returns true, it executes the ifTrue function and returns its result. If the condition function returns false, it executes the ifFalse function and returns its result.

This function is useful when you need to perform different operations and return a result based on a condition.

Example:

var age = 20;
var result = executeIfAs<String>(
  () => age >= 18,
  ifTrue: () => 'You are an adult.',
  ifFalse: () => 'You are not an adult.',
);
print(result); // prints: 'You are an adult.'

Generic type T can be any type and is used for the return type of the ifTrue and ifFalse functions.

Implementation

T executeIfAs<T>(
  bool Function() condition, {
  required T Function() ifTrue,
  required T Function() ifFalse,
}) {
  if (condition()) {
    return ifTrue();
  } else {
    return ifFalse();
  }
}