session-companion/SessionCompanion/SessionCompanion.Extensions/EitherType/Either.cs

70 lines
1.9 KiB
C#

using System;
namespace SessionCompanion.Extensions.EitherType
{
public class Either<TL, TR>
{
private readonly TL left;
private readonly TR right;
private readonly bool isLeft;
public Either(TL left)
{
this.left = left;
this.isLeft = true;
}
public Either(TR right)
{
this.right = right;
this.isLeft = false;
}
/// <summary>
/// Bazowa metoda dopasowania wzorów.
/// Jeśli podana jest wartość lewa, to Match zwróci wynik lewej funkcji, w przeciwnym razie wynik prawej funkcji.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="leftFunc">Lewa funkcja </param>
/// <param name="rightFunc">Prawa funkcja</param>
/// <returns>Wynik prawej/lewej funkcji</returns>
public T Match<T>(Func<TL, T> leftFunc, Func<TR, T> rightFunc)
{
if (leftFunc == null)
{
throw new ArgumentNullException(nameof(leftFunc));
}
if (rightFunc == null)
{
throw new ArgumentNullException(nameof(rightFunc));
}
return this.isLeft ? leftFunc(this.left) : rightFunc(this.right);
}
public void DoRight(Action<TR> rightAction)
{
if (rightAction == null)
{
throw new ArgumentNullException(nameof(rightAction));
}
if (!this.isLeft)
{
rightAction(this.right);
}
}
public TL LeftOrDefault() => this.Match(l => l, r => default(TL));
public TR RightOrDefault() => this.Match(l => default(TR), r => r);
public static implicit operator Either<TL, TR>(TL left) => new Either<TL, TR>(left);
public static implicit operator Either<TL, TR>(TR right) => new Either<TL, TR>(right);
}
}