fjfzeagle
7/23/2015 - 6:14 AM

If expression

If expression

(*
 * If expression - ternary operator like C.
 *
 * HOW TO USE
 *   1. uses uIfExp;
 *   2. IfExp<TYPE>(BooleanValue) - TRUE_VALUE or FALSE_VALUE
 *      or
 *      IfExp<TYPE>(BooleanValue).ThenElse(TRUE_VALUE, FALSE_VALUE);
 *
 * EXAMPLE
 *   Writeln(IfExp<String>(1 > 0) - 'true' or 'false');
 *   Writeln(IfExp<Integer>(1 > 3) - 100 or -100);
 *   Writeln(IfExp<Double>('a' > 'c').ThenElse(0.1, 0.2));
 *
 * Programmed by HOSOKAWA Jun / twitter: @pik
 *)

unit uIfExp;

interface

uses
  System.Rtti;

type
  IfExp<T> = record
  private class var
    FValue: Boolean;
    FThen: TValue;
  public
    class operator Implicit(const AValue: Boolean): IfExp<T>;
    class operator Subtract(
      const ALeft: IfExp<T>;
      const ARight: TValue): IfExp<T>;
    class operator BitwiseOr(const ALeft: IfExp<T>; const ARight: TValue): T;
    class function ThenElse(const AThen, AElse: T): T; static; inline;
  end;

implementation

{ IfThen<T> }

class operator IfExp<T>.BitwiseOr(
  const ALeft: IfExp<T>;
  const ARight: TValue): T;
begin
  if (FValue) then
    Result := FThen.AsType<T>
  else
    Result := ARight.AsType<T>;
end;

class operator IfExp<T>.Implicit(const AValue: Boolean): IfExp<T>;
begin
  FValue := AValue;
end;

class operator IfExp<T>.Subtract(
  const ALeft: IfExp<T>;
  const ARight: TValue): IfExp<T>;
begin
  FThen := ARight;
end;

class function IfExp<T>.ThenElse(const AThen, AElse: T): T;
begin
  if (FValue) then
    Result := AThen
  else
    Result := AElse;
end;

end.