From b6317a47e8c515ac85168cce699f986de252a2e8 Mon Sep 17 00:00:00 2001 From: thepaperpilot Date: Fri, 21 Apr 2023 23:47:33 -0500 Subject: [PATCH] Fix calculate max affordable edge case --- src/game/formulas/formulas.ts | 4 ++-- tests/game/formulas.test.ts | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/game/formulas/formulas.ts b/src/game/formulas/formulas.ts index 9f6ad5a..cdc4b0e 100644 --- a/src/game/formulas/formulas.ts +++ b/src/game/formulas/formulas.ts @@ -1426,14 +1426,14 @@ export function calculateMaxAffordable( summedPurchases = 0; } } - if (summedPurchases > 0) { + if (summedPurchases > 0 && Decimal.lt(calculateCost(formula, affordable, true, 0), 1e308)) { affordable = affordable.sub(summedPurchases).clampMin(0); let summedCost = calculateCost(formula, affordable, true, 0); while (true) { const nextCost = formula.evaluate( affordable.add(unref(formula.innermostVariable) ?? 0) ); - if (Decimal.add(summedCost, nextCost).lt(resource.value)) { + if (Decimal.add(summedCost, nextCost).lte(resource.value)) { affordable = affordable.add(1); summedCost = Decimal.add(summedCost, nextCost); } else { diff --git a/tests/game/formulas.test.ts b/tests/game/formulas.test.ts index 86ec8c4..69254cf 100644 --- a/tests/game/formulas.test.ts +++ b/tests/game/formulas.test.ts @@ -1174,6 +1174,24 @@ describe("Buy Max", () => { // Since we're summing all the purchases this should be equivalent expect(calculatedCost).compare_tolerance(actualCost); }); + test("Handles summing purchases when making very few purchases", () => { + const purchases = ref(0); + const variable = Formula.variable(purchases); + const formula = variable.add(1); + const resource = createResource(ref(3)); + const maxAffordable = calculateMaxAffordable(formula, resource, true); + expect(maxAffordable.value).compare_tolerance(2); + + const actualCost = new Array(2) + .fill(null) + .reduce( + (acc, _, i) => acc.add(formula.evaluate(i + purchases.value)), + new Decimal(0) + ); + const calculatedCost = calculateCost(formula, maxAffordable.value, true); + // Since we're summing all the purchases this should be equivalent + expect(calculatedCost).compare_tolerance(actualCost); + }); test("Handles summing purchases when over e308 purchases", () => { resource.value = "1ee308"; const purchases = ref(0);