Calculations in R6

This commit is contained in:
Michał Zieliński
2025-08-11 21:11:25 +02:00
parent 15ed0075ea
commit 41acf9f93e
2 changed files with 103 additions and 35 deletions

View File

@@ -40,6 +40,30 @@ public class BaseCalc
Formula.All(c => char.IsDigit(c) || c == '[' || c == ']' || c == '+' || c == '-');
}
public double Calculate(IReadOnlyDictionary<string, double> ingredients)
{
if (ingredients == null)
{
throw new ArgumentNullException(nameof(ingredients));
}
var codes = GetCodes();
var missing = codes.Where(x => !ingredients.ContainsKey(x)).ToList();
if (missing.Any())
{
throw new ArgumentException($"Missing ingredients: {string.Join(", ", missing)}");
}
var formula = ingredients.Aggregate(Formula,
(current, ingredient) => current.Replace($"[{ingredient.Key}]", ingredient.Value.ToString(CultureInfo.InvariantCulture)));
if (formula.Contains('['))
{
throw new Exception($"Not all placeholders were replaced. Value{1} [{formula}]");
}
Entity expr = formula;
return (double)expr.EvalNumerical();
}
public Record CalculateT3(List<Record> records)
{
var resultCode = ResultCode;
@@ -81,7 +105,6 @@ public class BaseCalc
return result;
}
}
public Record CalculateT1(List<Record> records)
{
var resultCode = ResultCode;
@@ -121,8 +144,7 @@ public class BaseCalc
return result;
}
}
private List<string> GetCodes()
public List<string> GetCodes()
{
var codes = new List<string>();
var endIndex = -1;
@@ -143,4 +165,9 @@ public class BaseCalc
return codes;
}
public string GetResultCode()
{
return ResultCode;
}
}