format, lint, more enums, revert fn rename

This commit is contained in:
Snarling 2022-10-05 14:52:48 -04:00
parent a78a84c5b5
commit 068533cd2f
23 changed files with 94 additions and 101 deletions

@ -86,34 +86,34 @@ export interface IBitNodeMultipliers {
* Influeces the hash rate of Hacknet Servers (unlocked in BitNode-9)
*/
HacknetNodeMoney: number;
/** Influences how much money it costs to upgrade your home computer's RAM */
HomeComputerRamCost: number;
/** Influences how much money is gained when the player infiltrates a company. */
InfiltrationMoney: number;
/** Influences how much rep the player can gain from factions when selling stolen documents and secrets */
InfiltrationRep: number;
/**
* Influences how much money can be stolen from a server when the player performs a hack against it through
* the Terminal.
*/
ManualHackMoney: number;
/** Influence how much it costs to purchase a server */
PurchasedServerCost: number;
/** Influence how much it costs to purchase a server */
PurchasedServerSoftcap: number;
/** Influences the maximum number of purchased servers you can have */
PurchasedServerLimit: number;
/** Influences the maximum allowed RAM for a purchased server */
PurchasedServerMaxRam: number;
/** Influences the minimum favor the player must have with a faction before they can donate to gain rep. */
RepToDonateToFaction: number;

@ -55,7 +55,7 @@ export function generateContract(params: IGenerateContractParams): void {
// Problem Type
let problemType;
const problemTypes = Object.keys(CodingContractTypes);
if (params.problemType != null && problemTypes.includes(params.problemType)) {
if (params.problemType && problemTypes.includes(params.problemType)) {
problemType = params.problemType;
} else {
problemType = getRandomProblemType();

@ -14,7 +14,7 @@ import { Cities } from "../Locations/Cities";
import { EmployeePositions } from "./EmployeePositions";
import { ResearchMap } from "./ResearchMap";
import { isRelevantMaterial } from "./ui/Helpers";
import { checkObjContainsValue } from "../utils/helpers/checkObjContains";
import { checkEnum } from "../utils/helpers/checkEnum";
export function NewIndustry(corporation: Corporation, industry: string, name: string): void {
if (corporation.divisions.find(({ type }) => industry == type))
@ -305,12 +305,12 @@ export function BuyBackShares(corporation: Corporation, numShares: number): bool
export function AssignJob(office: OfficeSpace, employeeName: string, job: string): void {
const employee = office.employees.find((e) => e.name === employeeName);
if (!employee) throw new Error(`Could not find employee '${name}'.`);
if (!checkObjContainsValue(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`)
if (!checkEnum(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`);
office.assignSingleJob(employee, job);
}
export function AutoAssignJob(office: OfficeSpace, job: string, count: number): boolean {
if (!checkObjContainsValue(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`)
if (!checkEnum(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`);
return office.autoAssignJob(job, count);
}

@ -1,9 +1,9 @@
export const EmployeePositions = {
Operations: "Operations",
Engineer: "Engineer",
Business: "Business",
Management: "Management",
RandD: "Research & Development",
Training: "Training",
Unassigned: "Unassigned",
} as const;
export enum EmployeePositions {
Operations = "Operations",
Engineer = "Engineer",
Business = "Business",
Management = "Management",
RandD = "Research & Development",
Training = "Training",
Unassigned = "Unassigned",
}

@ -602,6 +602,7 @@ export class Industry {
}
}
// TODO: Change all these Object.keys where the value is also needed to Object.entries.
// Use the materials already in the warehouse if the option is on.
for (const matName of Object.keys(smartBuy)) {
if (!warehouse.smartSupplyUseLeftovers[matName]) continue;
@ -612,9 +613,8 @@ export class Industry {
}
// buy them
for (const matName of Object.keys(smartBuy)) {
for (const [matName, buyAmt] of Object.entries(smartBuy)) {
const mat = warehouse.materials[matName];
const buyAmt = smartBuy[matName];
if (buyAmt === undefined) throw new Error(`Somehow smartbuy matname is undefined`);
mat.qty += buyAmt;
expenses += buyAmt * mat.bCost;

@ -1,23 +1,23 @@
export const LiteratureNames = {
HackersStartingHandbook: "hackers-starting-handbook.lit",
CorporationManagementHandbook: "corporation-management-handbook.lit",
HistoryOfSynthoids: "history-of-synthoids.lit",
AGreenTomorrow: "A-Green-Tomorrow.lit",
AlphaOmega: "alpha-omega.lit",
SimulatedReality: "simulated-reality.lit",
BeyondMan: "beyond-man.lit",
BrighterThanTheSun: "brighter-than-the-sun.lit",
DemocracyIsDead: "democracy-is-dead.lit",
Sector12Crime: "sector-12-crime.lit",
ManAndMachine: "man-and-machine.lit",
SecretSocieties: "secret-societies.lit",
TheFailedFrontier: "the-failed-frontier.lit",
CodedIntelligence: "coded-intelligence.lit",
SyntheticMuscles: "synthetic-muscles.lit",
TensionsInTechRace: "tensions-in-tech-race.lit",
CostOfImmortality: "cost-of-immortality.lit",
TheHiddenWorld: "the-hidden-world.lit",
TheNewGod: "the-new-god.lit",
NewTriads: "new-triads.lit",
TheSecretWar: "the-secret-war.lit",
} as const;
export enum LiteratureNames {
HackersStartingHandbook = "hackers-starting-handbook.lit",
CorporationManagementHandbook = "corporation-management-handbook.lit",
HistoryOfSynthoids = "history-of-synthoids.lit",
AGreenTomorrow = "A-Green-Tomorrow.lit",
AlphaOmega = "alpha-omega.lit",
SimulatedReality = "simulated-reality.lit",
BeyondMan = "beyond-man.lit",
BrighterThanTheSun = "brighter-than-the-sun.lit",
DemocracyIsDead = "democracy-is-dead.lit",
Sector12Crime = "sector-12-crime.lit",
ManAndMachine = "man-and-machine.lit",
SecretSocieties = "secret-societies.lit",
TheFailedFrontier = "the-failed-frontier.lit",
CodedIntelligence = "coded-intelligence.lit",
SyntheticMuscles = "synthetic-muscles.lit",
TensionsInTechRace = "tensions-in-tech-race.lit",
CostOfImmortality = "cost-of-immortality.lit",
TheHiddenWorld = "the-hidden-world.lit",
TheNewGod = "the-new-god.lit",
NewTriads = "new-triads.lit",
TheSecretWar = "the-secret-war.lit",
}

@ -3,7 +3,7 @@ import { NSFull } from "../NetscriptFunctions";
/** This type assumes any value that isn't an API layer or a function has been omitted (args and enum) */
type RamCostTree<API> = {
[Property in keyof API]: API[Property] extends Function ? number | (() => number) : RamCostTree<API[Property]>;
[Property in keyof API]: API[Property] extends () => unknown ? number | (() => number) : RamCostTree<API[Property]>;
};
/** Constants for assigning costs to ns functions */

@ -71,7 +71,7 @@ import { NetscriptSingularity } from "./NetscriptFunctions/Singularity";
import { dialogBoxCreate } from "./ui/React/DialogBox";
import { SnackbarEvents, ToastVariant } from "./ui/React/Snackbar";
import { checkObjContainsValue } from "./utils/helpers/checkObjContains";
import { checkEnum } from "./utils/helpers/checkEnum";
import { Flags } from "./NetscriptFunctions/Flags";
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
@ -85,7 +85,7 @@ import { ScriptDeath } from "./Netscript/ScriptDeath";
export const enums = {
toast: ToastVariant,
} as const;
export type NSFull = NS & INetscriptExtra;
export type NSFull = Readonly<NS & INetscriptExtra>;
export function NetscriptFunctions(workerScript: WorkerScript): NSFull {
return wrapAPI(workerScript, ns, workerScript.args.slice());
@ -1784,12 +1784,12 @@ const base: InternalAPI<NS> = {
},
toast:
(ctx: NetscriptContext) =>
(_message: unknown, _variant: unknown = enums.toast.SUCCESS, _duration: unknown = 2000): void => {
(_message: unknown, _variant: unknown = ToastVariant.SUCCESS, _duration: unknown = 2000): void => {
const message = helpers.string(ctx, "message", _message);
const variant = helpers.string(ctx, "variant", _variant);
const duration = _duration === null ? null : helpers.number(ctx, "duration", _duration);
if (!checkObjContainsValue(enums.toast, variant))
throw new Error(`variant must be one of ${Object.values(enums.toast).join(", ")}`);
if (!checkEnum(ToastVariant, variant))
throw new Error(`variant must be one of ${Object.values(ToastVariant).join(", ")}`);
SnackbarEvents.emit(message, variant as ToastVariant, duration);
},
prompt:
@ -1947,7 +1947,7 @@ const base: InternalAPI<NS> = {
};
// add undocumented functions
const ns = {
export const ns = {
...base,
...NetscriptExtra(),
};

@ -66,7 +66,7 @@ import { Factions } from "../Faction/Factions";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
import { checkObjContainsValue } from "../utils/helpers/checkObjContains";
import { checkEnum } from "../utils/helpers/checkEnum";
export function NetscriptCorporation(): InternalAPI<NSCorporation> {
function createCorporation(corporationName: string, selfFund = true): boolean {
@ -712,7 +712,7 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
const employeeName = helpers.string(ctx, "employeeName", _employeeName);
const job = helpers.string(ctx, "job", _job);
if (!checkObjContainsValue(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`);
if (!checkEnum(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`);
const office = getOffice(divisionName, cityName);
AssignJob(office, employeeName, job);
@ -726,7 +726,7 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
const amount = helpers.number(ctx, "amount", _amount);
const job = helpers.string(ctx, "job", _job);
if (!checkObjContainsValue(EmployeePositions,job)) throw new Error(`'${job}' is not a valid job.`);
if (!checkEnum(EmployeePositions, job)) throw new Error(`'${job}' is not a valid job.`);
const office = getOffice(divisionName, cityName);
return AutoAssignJob(office, job, amount);

@ -14,7 +14,7 @@ import {
import { FactionNames } from "../Faction/data/FactionNames";
import { Factions } from "../Faction/Factions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { checkObjContainsValue } from "../utils/helpers/checkObjContains";
import { checkEnum } from "../utils/helpers/checkEnum";
import { LocationName } from "../Locations/data/LocationNames";
import { helpers } from "../Netscript/NetscriptHelpers";
@ -24,7 +24,7 @@ export function NetscriptInfiltration(): InternalAPI<IInfiltration> {
);
const calculateInfiltrationData = (ctx: NetscriptContext, locationName: string): InfiltrationLocation => {
if (!checkObjContainsValue(LocationName, locationName)) throw new Error(`Location '${locationName}' does not exists.`);
if (!checkEnum(LocationName, locationName)) throw new Error(`Location '${locationName}' does not exists.`);
const location = Locations[locationName];
if (location === undefined) throw helpers.makeRuntimeErrorMsg(ctx, `Location '${location}' does not exists.`);
if (location.infiltrationData === undefined)

@ -11,7 +11,7 @@ import {
SleeveSkills,
SleeveTask,
} from "../ScriptEditor/NetscriptDefinitions";
import { checkObjContainsValue } from "../utils/helpers/checkObjContains";
import { checkEnum } from "../utils/helpers/checkEnum";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { isSleeveBladeburnerWork } from "../PersonObjects/Sleeve/Work/SleeveBladeburnerWork";
import { isSleeveFactionWork } from "../PersonObjects/Sleeve/Work/SleeveFactionWork";
@ -102,7 +102,7 @@ export function NetscriptSleeve(): InternalAPI<ISleeve> {
const cityName = helpers.string(ctx, "cityName", _cityName);
checkSleeveAPIAccess(ctx);
checkSleeveNumber(ctx, sleeveNumber);
if (checkObjContainsValue(CityName, cityName)) {
if (checkEnum(CityName, cityName)) {
return Player.sleeves[sleeveNumber].travel(cityName);
} else {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid city name: '${cityName}'.`);

@ -17,7 +17,7 @@ function giveSourceFile(bitNodeNumber: number): void {
}
// Check if player already has this source file
const ownedSourceFile = Player.sourceFiles.find(sourceFile=>sourceFile.n === bitNodeNumber)
const ownedSourceFile = Player.sourceFiles.find((sourceFile) => sourceFile.n === bitNodeNumber);
if (ownedSourceFile) {
if (ownedSourceFile.lvl >= 3 && ownedSourceFile.n !== 12) {

@ -707,7 +707,7 @@ function loadGame(saveString: string): boolean {
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
// Try to set saved settings.
// Try to set saved settings.
Settings.load(saveObj.SettingsSave);
} catch (e) {}
}

@ -4408,49 +4408,49 @@ export interface NS {
* @remarks RAM cost: 4 GB
*/
readonly hacknet: Hacknet;
/**
* Namespace for bladeburner functions.
* @remarks RAM cost: 0 GB
*/
readonly bladeburner: Bladeburner;
/**
* Namespace for codingcontract functions.
* @remarks RAM cost: 0 GB
*/
readonly codingcontract: CodingContract;
/**
* Namespace for gang functions.
* @remarks RAM cost: 0 GB
*/
readonly gang: Gang;
/**
* Namespace for sleeve functions.
* @remarks RAM cost: 0 GB
*/
readonly sleeve: Sleeve;
/**
* Namespace for stock functions.
* @remarks RAM cost: 0 GB
*/
readonly stock: TIX;
/**
* Namespace for formulas functions.
* @remarks RAM cost: 0 GB
*/
readonly formulas: Formulas;
/**
* Namespace for stanek functions.
* RAM cost: 0 GB
*/
readonly stanek: Stanek;
/**
* Namespace for infiltration functions.
* RAM cost: 0 GB
@ -6533,7 +6533,6 @@ declare const enums = {
} as const;
type ToastVariant = ValuesFrom<typeof enums.toast>;
export type NSEnums = typeof enums;
/**
* Corporation Office API

@ -65,13 +65,13 @@ export const Settings = {
/** Whether the game's sidebar is opened. */
IsSidebarOpened: true,
/** Theme colors. */
theme: {...defaultTheme},
theme: { ...defaultTheme },
/** Interface styles. */
styles: {...defaultStyles},
styles: { ...defaultStyles },
/** Character overview settings. */
overview: { x: 0, y: 0, opened: true },
/** Script editor theme data. */
EditorTheme: {...defaultMonacoTheme},
EditorTheme: { ...defaultMonacoTheme },
/** Order to display the player's owned Augmentations/Source Files. */
OwnedAugmentationsOrder: OwnedAugmentationsOrderSetting.AcquirementTime,
/** What order the Augmentations should be displayed in when purchasing from a Faction. */
@ -85,7 +85,7 @@ export const Settings = {
MonacoVim: false,
/** Word wrap setting for Script Editor. */
MonacoWordWrap: "off" as WordWrapOptions,
load(saveString: string) {
const save = JSON.parse(saveString);
save.theme && Object.assign(Settings.theme, save.theme);

@ -170,16 +170,13 @@ export function initStockMarket(): void {
}
export function initSymbolToStockMap(): void {
for (const name of Object.keys(StockSymbols) as Array<keyof typeof StockSymbols>) {
if (StockSymbols.hasOwnProperty(name)) {
const stock = StockMarket[name];
if (stock == null) {
console.error(`Could not find Stock for ${name}`);
continue;
}
const symbol = StockSymbols[name];
SymbolToStockMap[symbol] = stock;
for (const [name, symbol] of Object.entries(StockSymbols)) {
const stock = StockMarket[name];
if (stock == null) {
console.error(`Could not find Stock for ${name}`);
continue;
}
SymbolToStockMap[symbol] = stock;
}
}

@ -1,5 +1,6 @@
import { LocationName } from "../../Locations/data/LocationNames";
//Enum-like object because some keys are created via code and have spaces. Membership can still be checked with checkEnum.
export const StockSymbols = {
// Stocks for companies at which you can work
[LocationName.AevumECorp]: "ECP",

@ -5,7 +5,7 @@ export const TickerHeaderFormatData = {
longestSymbol: 0,
};
for (const key of Object.keys(StockSymbols) as Array<keyof typeof StockSymbols>) {
for (const [key, symbol] of Object.entries(StockSymbols)) {
TickerHeaderFormatData.longestName = Math.max(key.length, TickerHeaderFormatData.longestName);
TickerHeaderFormatData.longestSymbol = Math.max(StockSymbols[key].length, TickerHeaderFormatData.longestSymbol);
TickerHeaderFormatData.longestSymbol = Math.max(symbol.length, TickerHeaderFormatData.longestSymbol);
}

@ -3,7 +3,7 @@ import { BaseServer } from "../../Server/BaseServer";
import { MessageFilenames, showMessage } from "../../Message/MessageHelpers";
import { showLiterature } from "../../Literature/LiteratureHelpers";
import { dialogBoxCreate } from "../../ui/React/DialogBox";
import { checkObjContainsValue } from "../../utils/helpers/checkObjContains";
import { checkEnum } from "../../utils/helpers/checkEnum";
export function cat(args: (string | number | boolean)[], server: BaseServer): void {
if (args.length !== 1) {
@ -35,7 +35,7 @@ export function cat(args: (string | number | boolean)[], server: BaseServer): vo
} else if (filename.endsWith(".msg")) {
const file = server.messages[i];
if (file !== filename) continue;
if (!checkObjContainsValue(MessageFilenames, file)) return;
if (!checkEnum(MessageFilenames, file)) return;
showMessage(file);
return;
}

@ -145,8 +145,7 @@ const Engine: {
},
decrementAllCounters: function (numCycles = 1) {
for (const counterName of Object.keys(Engine.Counters)) {
const counter = Engine.Counters[counterName];
for (const [counterName, counter] of Object.entries(Engine.Counters)) {
if (counter === undefined) throw new Error("counter should not be undefined");
Engine.Counters[counterName] = counter - numCycles;
}

@ -2,7 +2,7 @@ import React, { useEffect } from "react";
import { useSnackbar, SnackbarProvider as SB } from "notistack";
import makeStyles from "@mui/styles/makeStyles";
import { EventEmitter } from "../../utils/EventEmitter";
import Alert, { AlertColor } from "@mui/material/Alert";
import Alert from "@mui/material/Alert";
import Paper from "@mui/material/Paper";
import { logBoxBaseZIndex } from "./LogBoxManager";
@ -10,12 +10,12 @@ interface IProps {
children: React.ReactNode | React.ReactNode[];
}
export enum ToastVariant{
export enum ToastVariant {
SUCCESS = "success",
WARNING = "warning",
ERROR = "error",
INFO = "info",
};
}
const useStyles = makeStyles(() => ({
snackbar: {

@ -0,0 +1,4 @@
// This works for both enums and regular objects.
export function checkEnum<T extends Record<string, unknown>>(obj: T, value: unknown): value is T[keyof T] {
return Object.values(obj).includes(value);
}

@ -1,7 +0,0 @@
// This works for both enums and regular objects.
export function checkObjContainsValue<T extends Record<string, string>>(
obj: T,
value: string,
): value is T[keyof T] {
return Object.values(obj).includes(value);
}