Implemented Product.cs

This commit is contained in:
MarcUs7i 2025-03-19 21:53:10 +01:00
parent e67c72f20f
commit dedbe0b6f8

View file

@ -8,9 +8,9 @@ public abstract class Product
protected Product(string productName, string barcode, int quantity)
{
// TODO
ProductName = null!;
Barcode = null!;
ProductName = productName;
Barcode = IsBarcodeValid(barcode) ? barcode : Invalid;
Quantity = quantity > 0 ? quantity : 0;
}
public string ProductName { get; }
@ -19,30 +19,80 @@ public abstract class Product
public int Quantity { get; }
// TODO
protected virtual string[] CsvColumnNames => null!;
protected virtual string[] CsvColumnNames => [nameof(Barcode), nameof(ProductName), nameof(Quantity)];
// TODO
protected virtual string[] CsvColumnValues => null!;
protected virtual string[] CsvColumnValues => [Barcode, ProductName, Quantity.ToString()];
// TODO
public string GetCsvHeader() => null!;
public string GetCsvHeader()
{
string header = String.Empty;
foreach (var columnName in CsvColumnNames)
{
header += $"{columnName}{Separator}";
}
return header;
}
// TODO
public string ToCsv() => null!;
public string ToCsv() => ToCsvLine(CsvColumnValues, Separator);
// TODO
protected static string ToCsvLine(string[] values, char separator) => null!;
protected static string ToCsvLine(string[] values, char separator)
{
string line = string.Empty;
foreach (var value in values)
{
line += $"{value}{separator}";
}
return line;
}
public static bool IsBarcodeValid(string? barcode)
{
// TODO
if (barcode == null)
{
return false;
}
if(barcode.Length is > 8 or < 8)
{
return false;
}
const int evenWeight = 3;
const int oddWeight = 1;
int weight = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (!char.IsDigit(barcode[i]))
{
return false;
}
// Skip check digit
if (i == 7)
{
break;
}
int digit = int.Parse(barcode[i].ToString());
weight += i % 2 == 0 ? digit * evenWeight : digit * oddWeight;
}
int calculatedCheckDigit = 10 - (weight % 10);
if (calculatedCheckDigit == 10)
{
calculatedCheckDigit = 0;
}
return calculatedCheckDigit == int.Parse(barcode[^1].ToString());
}
protected static T[] AppendToArray<T>(T[] existingArray, params T[] newValues)
{
// TODO
return null!;
// we are allowed to use Lists, so why not? :)
List<T> result = new(existingArray.Length + newValues.Length);
result.AddRange(existingArray);
result.AddRange(newValues);
return result.ToArray();
}
}