From 7995d753887181d20e5b7fc8be4037adb3f65027 Mon Sep 17 00:00:00 2001
From: ezsh <ezsh.junk@gmail.com>
Date: Mon, 3 Jan 2022 22:40:22 +0100
Subject: [PATCH] Add explicit function for autosurgery procedures sorting

---
 src/js/rulesAutosurgery.js | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/src/js/rulesAutosurgery.js b/src/js/rulesAutosurgery.js
index e0c0fd841eb..0c890fbf10d 100644
--- a/src/js/rulesAutosurgery.js
+++ b/src/js/rulesAutosurgery.js
@@ -91,6 +91,15 @@ globalThis.rulesAutosurgery = (function() {
 			surgeryDamage(slave, healthCost);
 		}
 
+		/**
+		 * Computes procedure efficiency for selecting the best one
+		 * @param {App.Medicine.Surgery.Procedure} proc
+		 */
+		function procedureEfficiency(proc) {
+			const value = typeof proc.changeValue === "number" ? proc.changeValue : 1.;
+			return (value / proc.cost + value/proc.healthCost);
+		}
+
 		/**
 		 * @param {"boobs"|"butt"} bodyPart
 		 * @param {!FC.RA.NumericRange} range
@@ -102,11 +111,12 @@ globalThis.rulesAutosurgery = (function() {
 			const shallGrow = distance > 0;
 			/** @type {FC.Medicine.Surgery.SizingOptions} */
 			const options = {
-				types: implantTypes.length ? implantTypes : null // we can't set null via RA UI :(
+				types: implantTypes && implantTypes.length ? implantTypes : null // we can't set null via RA UI :(
 			};
 			options.strictTypes = options.types && options.types.length > 0;
 			const shallReplaceImplantType = slave[`${bodyPart}Implant`] > 0 &&
 				options.types && !options.types.some(v => v === slave[`${bodyPart}ImplantType`]);
+			/** @type {(left: App.Medicine.Surgery.Procedure, right: App.Medicine.Surgery.Procedure) => number} */
 			let sorter;
 			if (shallShrink) {
 				if (range.max === 0) {
@@ -114,11 +124,11 @@ globalThis.rulesAutosurgery = (function() {
 				}
 				options.reduction = true;
 				options.replace = true;
-				sorter = (left, right) => -right.targetEffect / right.costs + left.targetEffect / left.costs;
+				sorter = (left, right) => -procedureEfficiency(right) + procedureEfficiency(left);
 			} else if (shallGrow) {
 				options.augmentation = true;
 				options.replace = true;
-				sorter = (left, right) => right.targetEffect / right.costs - left.targetEffect / left.costs;
+				sorter = (left, right) => procedureEfficiency(right) - procedureEfficiency(left);
 			}
 			if (!shallShrink && !shallGrow && !shallReplaceImplantType) {
 				return;
@@ -128,7 +138,7 @@ globalThis.rulesAutosurgery = (function() {
 				// we allow implant removal because there might be no other way to change its type
 				options.types = options.types ? [...options.types, "none"] : ["none"];
 				options.reduction = true;
-				sorter = (left, right) => right.targetEffect / right.costs - left.targetEffect / left.costs;
+				sorter = (left, right) => procedureEfficiency(right) - procedureEfficiency(left);
 			}
 
 			/**
-- 
GitLab