Skip to content

Commit

Permalink
CODEBASE: Fix lint errors 2 (#1756)
Browse files Browse the repository at this point in the history
  • Loading branch information
catloversg authored Nov 7, 2024
1 parent e3c10e9 commit 36c143b
Show file tree
Hide file tree
Showing 48 changed files with 267 additions and 146 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ module.exports = {
"@typescript-eslint/no-explicit-any": "off",
"react/no-unescaped-entities": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/no-unsafe-enum-comparison": "off",
},
settings: {
react: {
Expand Down
11 changes: 11 additions & 0 deletions src/@types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,14 @@ declare global {
}
}
}

module "monaco-vim" {
export const initVimMode: (...args: unknown[]) => { dispose: () => void };
export const VimMode: {
Vim: {
defineEx: (...args: unknown[]) => void;
mapCommand: (...args: unknown[]) => void;
defineAction: (...args: unknown[]) => void;
};
};
}
3 changes: 2 additions & 1 deletion src/Casino/CardDeck/ReactCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Card, Suit } from "./Card";

import { makeStyles } from "tss-react/mui";
import Paper from "@mui/material/Paper";
import { throwIfReachable } from "../../utils/helpers/throwIfReachable";

interface Props {
card: Card;
Expand Down Expand Up @@ -51,7 +52,7 @@ export const ReactCard: FC<Props> = ({ card, hidden }) => {
suit = <span>&#9824;</span>;
break;
default:
throw new Error(`MissingCaseException: ${card.suit}`);
throwIfReachable(card.suit);
}
return (
<Paper className={`${classes.card} ${card.isRedSuit() ? classes.red : classes.black}`}>
Expand Down
8 changes: 5 additions & 3 deletions src/Company/GetJobRequirements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { Company } from "./Company";
import { CompanyPosition } from "./CompanyPosition";

import { PlayerCondition, haveSkill, haveCompanyRep } from "../Faction/FactionJoinCondition";
import type { Skills } from "../PersonObjects/Skills";
import { getRecordEntries } from "../Types/Record";

export function getJobRequirements(company: Company, pos: CompanyPosition): PlayerCondition[] {
const reqSkills = pos.requiredSkills(company.jobStatReqOffset);
const reqs = [];
for (const [skillName, value] of Object.entries(reqSkills)) {
if (value > 0) reqs.push(haveSkill(skillName as keyof Skills, value));
for (const [skillName, value] of getRecordEntries(reqSkills)) {
if (value > 0) {
reqs.push(haveSkill(skillName, value));
}
}
if (pos.requiredReputation > 0) {
reqs.push(haveCompanyRep(company.name, pos.requiredReputation));
Expand Down
56 changes: 43 additions & 13 deletions src/Corporation/Corporation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { dialogBoxCreate } from "../ui/React/DialogBox";
import { constructorsForReviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver";
import { JSONMap, JSONSet } from "../Types/Jsonable";
import { formatMoney } from "../ui/formatNumber";
import { isPositiveInteger } from "../types";
import { isPositiveInteger, type Result } from "../types";
import { createEnumKeyedRecord, getRecordValues } from "../Types/Record";
import { getKeyList } from "../utils/helpers/getKeyList";

Expand Down Expand Up @@ -372,29 +372,56 @@ export class Corporation {
}
}

/** Purchasing a one-time unlock
* @returns A string on failure, indicating the reason for failure. */
purchaseUnlock(unlockName: CorpUnlockName): string | void {
if (this.unlocks.has(unlockName)) return `The corporation has already unlocked ${unlockName}`;
/**
* Purchasing a one-time unlock
*/
purchaseUnlock(unlockName: CorpUnlockName): Result {
if (this.unlocks.has(unlockName)) {
return {
success: false,
message: `${unlockName} has already been unlocked.`,
};
}
const price = CorpUnlocks[unlockName].price;
if (this.funds < price) return `Insufficient funds to purchase ${unlockName}, requires ${formatMoney(price)}`;
if (this.funds < price) {
return {
success: false,
message: `Insufficient funds to purchase ${unlockName}, requires ${formatMoney(price)}.`,
};
}
this.loseFunds(price, "upgrades");
this.unlocks.add(unlockName);

// Apply effects for one-time unlocks
if (unlockName === CorpUnlockName.ShadyAccounting) this.dividendTax -= 0.05;
if (unlockName === CorpUnlockName.GovernmentPartnership) this.dividendTax -= 0.1;
if (unlockName === CorpUnlockName.ShadyAccounting) {
this.dividendTax -= 0.05;
}
if (unlockName === CorpUnlockName.GovernmentPartnership) {
this.dividendTax -= 0.1;
}
return {
success: true,
};
}

/** Purchasing a levelable upgrade
* @returns A string on failure, indicating the reason for failure. */
purchaseUpgrade(upgradeName: CorpUpgradeName, amount = 1): string | void {
/**
* Purchasing a levelable upgrade
*/
purchaseUpgrade(upgradeName: CorpUpgradeName, amount = 1): Result {
if (!isPositiveInteger(amount)) {
return `Number of upgrade levels purchased must be a positive integer (attempted: ${amount}).`;
return {
success: false,
message: `Number of upgrade levels purchased must be a positive integer (attempted: ${amount}).`,
};
}
const upgrade = CorpUpgrades[upgradeName];
const totalCost = calculateUpgradeCost(this, upgrade, amount);
if (this.funds < totalCost) return `Not enough funds to purchase ${amount} of upgrade ${upgradeName}.`;
if (this.funds < totalCost) {
return {
success: false,
message: `Not enough funds to purchase ${amount} of upgrade ${upgradeName}.`,
};
}
this.loseFunds(totalCost, "upgrades");
this.upgrades[upgradeName].level += amount;
this.upgrades[upgradeName].value += upgrade.benefit * amount;
Expand All @@ -407,6 +434,9 @@ export class Corporation {
}
}
}
return {
success: true,
};
}

getProductionMultiplier(): number {
Expand Down
7 changes: 3 additions & 4 deletions src/Corporation/Division.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { PartialRecord, getRecordEntries, getRecordKeys, getRecordValues } from
import { Material } from "./Material";
import { getKeyList } from "../utils/helpers/getKeyList";
import { calculateMarkupMultiplier } from "./helpers";
import { throwIfReachable } from "../utils/helpers/throwIfReachable";

interface DivisionParams {
name: string;
Expand Down Expand Up @@ -704,8 +705,7 @@ export class Division {
case "START":
break;
default:
console.error(`Invalid state: ${state}`);
break;
throwIfReachable(state);
} //End switch(this.state)
this.updateWarehouseSizeUsed(warehouse);
}
Expand Down Expand Up @@ -936,8 +936,7 @@ export class Division {
case "EXPORT":
break;
default:
console.error(`Invalid State: ${state}`);
break;
throwIfReachable(state);
} //End switch(this.state)
this.updateWarehouseSizeUsed(warehouse);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Corporation/OfficeSpace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Division } from "./Division";
import { Corporation } from "./Corporation";
import { getRandomIntInclusive } from "../utils/helpers/getRandomIntInclusive";
import { createEnumKeyedRecord, getRecordKeys } from "../Types/Record";
import { throwIfReachable } from "../utils/helpers/throwIfReachable";

interface IParams {
city: CityName;
Expand Down Expand Up @@ -165,8 +166,7 @@ export class OfficeSpace {
case "total":
continue;
default:
console.error(`Invalid employee position: ${name}`);
break;
throwIfReachable(name);
}
this.employeeProductionByJob[name] = this.employeeJobs[name] * prodMult * prodBase;
total += this.employeeProductionByJob[name];
Expand Down
4 changes: 3 additions & 1 deletion src/Corporation/Product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,9 @@ export class Product {

calculateRating(industry: Division): void {
const weights = IndustriesData[industry.type].product?.ratingWeights;
if (!weights) return console.error(`Could not find product rating weights for: ${industry}`);
if (!weights) {
return console.error(`Could not find product rating weights for: ${industry.name}`);
}
this.rating = getRecordEntries(weights).reduce(
(total, [statName, weight]) => total + this.stats[statName] * weight,
0,
Expand Down
6 changes: 4 additions & 2 deletions src/Corporation/ui/LevelableUpgrade.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ export function LevelableUpgrade({ upgradeName, mult, rerender }: IProps): React
const tooltip = data.desc;
function onClick(): void {
if (corp.funds < cost) return;
const message = corp.purchaseUpgrade(upgradeName, amount);
if (message) dialogBoxCreate(`Could not upgrade ${upgradeName} ${amount} times:\n${message}`);
const result = corp.purchaseUpgrade(upgradeName, amount);
if (!result.success) {
dialogBoxCreate(`Could not upgrade ${upgradeName} ${amount} times:\n${result.message}`);
}
rerender();
}

Expand Down
6 changes: 4 additions & 2 deletions src/Corporation/ui/Unlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ export function Unlock(props: UnlockProps): React.ReactElement {

function onClick(): void {
// corp.unlock handles displaying a dialog on failure
const message = corp.purchaseUnlock(props.name);
if (message) dialogBoxCreate(`Error while attempting to purchase ${props.name}:\n${message}`);
const result = corp.purchaseUnlock(props.name);
if (!result.success) {
dialogBoxCreate(`Error while attempting to purchase ${props.name}:\n${result.message}`);
}
// Rerenders the parent, which should remove this item if the purchase was successful
props.rerender();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Corporation/ui/modals/SellSharesModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export function SellSharesModal(props: IProps): React.ReactElement {
props.onClose();
props.rerender();
setShares(NaN);
} catch (err) {
dialogBoxCreate(`${err as Error}`);
} catch (error) {
dialogBoxCreate(String(error));
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/CotMG/Helper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ export let staneksGift = new StaneksGift();

export function loadStaneksGift(saveString: string): void {
if (saveString) {
staneksGift = JSON.parse(saveString, Reviver);
staneksGift = JSON.parse(saveString, Reviver) as StaneksGift;
} else {
staneksGift = new StaneksGift();
}
}

export function zeros(width: number, height: number): number[][] {
const array = [];
const array: number[][] = [];

for (let i = 0; i < width; ++i) {
array.push(Array(height).fill(0));
array.push(Array<number>(height).fill(0));
}

return array;
Expand Down
3 changes: 0 additions & 3 deletions src/CotMG/StaneksGift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ export class StaneksGift extends BaseGift {
isBonusCharging = false;
justCharged = true;
storedCycles = 0;
constructor() {
super();
}

baseSize(): number {
return StanekConstants.BaseSize + currentNodeMults.StaneksGiftExtraSize + Player.activeSourceFileLvl(13);
Expand Down
18 changes: 16 additions & 2 deletions src/GameOptions/ui/GameOptionsSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,27 @@ export const GameOptionsSidebar = (props: IProps): React.ReactElement => {
>
<Button onClick={startImport} startIcon={<Upload />} sx={{ gridArea: "import" }}>
Import Game
<input ref={importInput} id="import-game-file-selector" type="file" hidden onChange={onImport} />
<input
ref={importInput}
id="import-game-file-selector"
type="file"
hidden
onChange={(event) => {
onImport(event).catch((error) => {
console.error(error);
});
}}
/>
</Button>
</Tooltip>
<ConfirmationModal
open={importSaveOpen}
onClose={() => setImportSaveOpen(false)}
onConfirm={() => confirmedImportGame()}
onConfirm={() => {
confirmedImportGame().catch((error) => {
console.error(error);
});
}}
additionalButton={<Button onClick={compareSaveGame}>Compare Save</Button>}
confirmationText={
<>
Expand Down
3 changes: 2 additions & 1 deletion src/Gang/ui/GangMemberStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { Settings } from "../../Settings/Settings";
import { MoneyRate } from "../../ui/React/MoneyRate";
import { StatsRow } from "../../ui/React/StatsRow";
import { useStyles } from "../../ui/React/CharacterOverview";
import { getKeyFromReactElements } from "../../utils/StringHelperFunctions";

interface IProps {
member: GangMember;
Expand Down Expand Up @@ -103,7 +104,7 @@ export function GangMemberStats(props: IProps): React.ReactElement {
</TableCell>
</TableRow>
{data.map(([a, b]) => (
<TableRow key={a.toString() + b.toString()}>
<TableRow key={getKeyFromReactElements(a, b)}>
<TableCell classes={{ root: classes.cellNone }}>
<Typography>{a}</Typography>
</TableCell>
Expand Down
6 changes: 5 additions & 1 deletion src/Go/SaveLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ export function loadGo(data: unknown): boolean {
Go.storeCycles(loadStoredCycles(parsedData.storedCycles));

// If it's the AI's turn, initiate their turn, which will populate nextTurn
if (currentGame.previousPlayer === GoColor.black && currentGame.ai !== GoOpponent.none) makeAIMove(currentGame);
if (currentGame.previousPlayer === GoColor.black && currentGame.ai !== GoOpponent.none) {
makeAIMove(currentGame).catch((error) => {
showError(error);
});
}
// If it's not the AI's turn and we're not in gameover status, initialize nextTurn promise based on the previous move/pass
else if (currentGame.previousPlayer) {
const previousMove = getPreviousMove();
Expand Down
2 changes: 1 addition & 1 deletion src/Infiltration/ui/MinesweeperGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export function MinesweeperGame(props: IMinigameProps): React.ReactElement {

return (
<Typography
key={`${item}${uniqueId()}`}
key={uniqueId()}
sx={{
color: color,
border: `2px solid ${item.current ? Settings.theme.infolight : Settings.theme.primary}`,
Expand Down
4 changes: 2 additions & 2 deletions src/Netscript/APIWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,15 @@ class NSProxyHandler<API extends GenericAPI<API>> {

const descriptor = Object.getOwnPropertyDescriptor(this.ns, key);
if (!descriptor) return descriptor;
const field = descriptor.value;
const field: unknown = descriptor.value;

if (typeof field === "function") {
const arrayPath = [...this.tree, key];
const functionPath = arrayPath.join(".");
const ctx = { workerScript: this.ws, function: key, functionPath };
// Only do the context-binding once, instead of each time the function
// is called.
const func: any = field(ctx);
const func = field(ctx) as (...args: unknown[]) => unknown;
const wrappedFunction = function (...args: unknown[]): unknown {
// What remains *must* be called every time.
helpers.checkEnvFlags(ctx);
Expand Down
7 changes: 5 additions & 2 deletions src/Netscript/NetscriptHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -692,8 +692,11 @@ function getRunningScript(ctx: NetscriptContext, ident: ScriptIdentifier): Runni
return findRunningScriptByPid(ident);
} else {
const scripts = getRunningScriptsByArgs(ctx, ident.scriptname, ident.hostname, ident.args);
if (scripts === null) return null;
return scripts.values().next().value ?? null;
if (scripts === null) {
return null;
}
const next = scripts.values().next();
return !next.done ? next.value : null;
}
}

Expand Down
12 changes: 8 additions & 4 deletions src/NetscriptFunctions/Corporation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,15 +624,19 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
checkAccess(ctx);
const unlockName = getEnumHelper("CorpUnlockName").nsGetMember(ctx, _unlockName, "unlockName");
const corporation = getCorporation();
const message = corporation.purchaseUnlock(unlockName);
if (message) throw new Error(`Could not unlock ${unlockName}: ${message}`);
const result = corporation.purchaseUnlock(unlockName);
if (!result.success) {
throw new Error(`Could not unlock ${unlockName}: ${result.message}`);
}
},
levelUpgrade: (ctx) => (_upgradeName) => {
checkAccess(ctx);
const upgradeName = getEnumHelper("CorpUpgradeName").nsGetMember(ctx, _upgradeName, "upgradeName");
const corporation = getCorporation();
const message = corporation.purchaseUpgrade(upgradeName, 1);
if (message) throw new Error(`Could not upgrade ${upgradeName}: ${message}`);
const result = corporation.purchaseUpgrade(upgradeName, 1);
if (!result.success) {
throw new Error(`Could not upgrade ${upgradeName}: ${result.message}`);
}
},
issueDividends: (ctx) => (_rate) => {
checkAccess(ctx);
Expand Down
Loading

0 comments on commit 36c143b

Please sign in to comment.