Skip to content

Instantly share code, notes, and snippets.

@keithn
Last active April 9, 2024 17:51
Show Gist options
  • Save keithn/ceeeed5f7eb567e1b2333747065d10dd to your computer and use it in GitHub Desktop.
Save keithn/ceeeed5f7eb567e1b2333747065d10dd to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Immutable;
namespace ConsoleDU
{
record CartItem(string Value);
record Payment(decimal Amount);
abstract record Cart
{
public record Empty () : Cart
{
public new static Active Add(CartItem item) => new(ImmutableList.Create(item));
}
public record Active (ImmutableList<CartItem> UnpaidItems) : Cart
{
public new Active Add(CartItem item) => this with {UnpaidItems = UnpaidItems.Add(item)};
public new Cart Remove(CartItem item) => this with {UnpaidItems = UnpaidItems.Remove(item)} switch
{
var (items) when items.IsEmpty => new Empty(),
{ } active => active
};
public new Cart Pay(decimal amount) => new PaidFor(UnpaidItems, new(amount));
}
public record PaidFor (ImmutableList<CartItem> PaidItems, Payment Payment) : Cart;
public Cart Display()
{
Console.WriteLine(this switch
{
Empty => "Cart is Empty",
Active cart => $"Cart has {cart.UnpaidItems.Count} items",
PaidFor(var items, var payment) => $"Cart has {items.Count} paid items. Amount paid: {payment.Amount}",
_ => "Unknown"
});
return this;
}
public Cart Add(CartItem item) => this switch
{
Empty state => Empty.Add(item),
Active state => state.Add(item),
_ => this
};
public static Cart NewCart => new Empty();
public Cart Remove(CartItem item) => this switch
{
Active state => state.Remove(item),
_ => this
};
public Cart Pay(decimal amount) => this switch
{
Active cart => cart.Pay(amount),
_ => this
};
}
class Program
{
static void Main(string[] args)
{
Cart.NewCart
.Display()
.Add(new("apple"))
.Add(new("orange"))
.Display()
.Remove(new("orange"))
.Display()
.Remove(new("apple"))
.Display()
.Add(new("orange"))
.Pay(23M)
.Display();
;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment