-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
ProductItemsList.cs
43 lines (31 loc) · 1.25 KB
/
ProductItemsList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace ECommerce.ShoppingCarts.ProductItems;
public class ProductItemsList(List<PricedProductItem> items)
{
public ProductItemsList Add(PricedProductItem productItem)
{
var clone = new List<PricedProductItem>(items);
var currentProductItem = Find(productItem);
if (currentProductItem == null)
clone.Add(productItem);
else
clone[clone.IndexOf(currentProductItem)] = currentProductItem.MergeWith(productItem);
return new ProductItemsList(clone);
}
public ProductItemsList Remove(PricedProductItem productItem)
{
var clone = new List<PricedProductItem>(items);
var currentProductItem = Find(productItem);
if (currentProductItem == null)
throw new InvalidOperationException("Product item wasn't found");
clone.Remove(currentProductItem);
return new ProductItemsList(clone);
}
public PricedProductItem? Find(PricedProductItem productItem) =>
items.SingleOrDefault(
pi => pi.MatchesProductAndUnitPrice(productItem)
);
public static ProductItemsList Empty() =>
new([]);
public override string ToString() =>
$"[{string.Join(", ", items.Select(pi => pi.ToString()))}]";
}