0
0
mirror of https://github.com/sp-tarkov/server.git synced 2025-02-13 09:50:43 -05:00

Biome Linting Issues

Fixed some instances of:
- Unordered imports
- Reassigning function parameters
- Modifying values in assignment/return statements
- Array.forEach being used instead of for...of
- Simplified control logic
This commit is contained in:
Refringe 2024-02-03 01:21:03 -05:00
parent d0ed738c0b
commit 34121182a1
No known key found for this signature in database
GPG Key ID: 64E03E5F892C6F9E
10 changed files with 85 additions and 58 deletions

View File

@ -2,11 +2,11 @@ import crypto from "node:crypto";
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import pkg from "@yao-pkg/pkg";
import pkgfetch from "@yao-pkg/pkg-fetch";
import gulp from "gulp"; import gulp from "gulp";
import { exec } from "gulp-execa"; import { exec } from "gulp-execa";
import rename from "gulp-rename"; import rename from "gulp-rename";
import pkg from "@yao-pkg/pkg";
import pkgfetch from "@yao-pkg/pkg-fetch";
import * as ResEdit from "resedit"; import * as ResEdit from "resedit";
import manifest from "./package.json" assert { type: "json" }; import manifest from "./package.json" assert { type: "json" };

View File

@ -207,7 +207,7 @@ export class RagfairController
{ {
offerPool = offers; offerPool = offers;
} }
else if ((!this.isLinkedSearch(searchRequest) && !this.isRequiredSearch(searchRequest))) else if ((!(this.isLinkedSearch(searchRequest) || this.isRequiredSearch(searchRequest))))
{ {
// Get all categories // Get all categories
offerPool = this.ragfairOfferService.getOffers(); offerPool = this.ragfairOfferService.getOffers();
@ -509,16 +509,14 @@ export class RagfairController
{ {
if (!offerRequest?.items || offerRequest.items.length === 0) if (!offerRequest?.items || offerRequest.items.length === 0)
{ {
errorMessage = this.localisationService.getText("ragfair-invalid_player_offer_request"); this.logger.error(this.localisationService.getText("ragfair-invalid_player_offer_request"));
this.logger.error(errorMessage);
return false; return false;
} }
if (!offerRequest.requirements) if (!offerRequest.requirements)
{ {
errorMessage = this.localisationService.getText("ragfair-unable_to_place_offer_with_no_requirements"); this.logger.error(this.localisationService.getText("ragfair-unable_to_place_offer_with_no_requirements"));
this.logger.error(errorMessage);
return false; return false;
} }
@ -725,7 +723,11 @@ export class RagfairController
{ {
const count = playerOffers[playerOfferIndex].sellInOnePiece const count = playerOffers[playerOfferIndex].sellInOnePiece
? 1 ? 1
: playerOffers[playerOfferIndex].items.reduce((sum, item) => sum += item.upd.StackObjectsCount, 0); : playerOffers[playerOfferIndex].items.reduce((sum, item) =>
{
return sum + item.upd.StackObjectsCount;
}, 0);
const tax = this.ragfairTaxService.calculateTax( const tax = this.ragfairTaxService.calculateTax(
playerOffers[playerOfferIndex].items[0], playerOffers[playerOfferIndex].items[0],
this.profileHelper.getPmcProfile(sessionId), this.profileHelper.getPmcProfile(sessionId),

View File

@ -276,11 +276,11 @@ export class RepeatableQuestController
{ {
element._id = this.objectId.generate(); element._id = this.objectId.generate();
const conditions = element.conditions.AvailableForFinish; const conditions = element.conditions.AvailableForFinish;
for (const element of conditions) for (const condition of conditions)
{ {
if ("counter" in element._props) if ("counter" in condition._props)
{ {
element._props.counter.id = this.objectId.generate(); condition._props.counter.id = this.objectId.generate();
} }
} }
} }

View File

@ -202,7 +202,6 @@ export class ProfileHelper
level = expTable.length - 1; level = expTable.length - 1;
} }
// TODO: Replace with exp = expTable.slice(0, level).reduce((acc, curr) => acc + curr.exp, 0);
for (let i = 0; i < level; i++) for (let i = 0; i < level; i++)
{ {
exp += expTable[i].exp; exp += expTable[i].exp;
@ -413,7 +412,6 @@ export class ProfileHelper
if (!profileSkills) if (!profileSkills)
{ {
this.logger.warning(`Unable to add ${pointsToAdd} points to ${skill}, profile has no skills`); this.logger.warning(`Unable to add ${pointsToAdd} points to ${skill}, profile has no skills`);
return; return;
} }
@ -421,7 +419,6 @@ export class ProfileHelper
if (!profileSkill) if (!profileSkill)
{ {
this.logger.error(this.localisationService.getText("quest-no_skill_found", skill)); this.logger.error(this.localisationService.getText("quest-no_skill_found", skill));
return; return;
} }
@ -429,7 +426,7 @@ export class ProfileHelper
{ {
const globals = this.databaseServer.getTables().globals; const globals = this.databaseServer.getTables().globals;
const skillProgressRate = globals.config.SkillsSettings.SkillProgressRate; const skillProgressRate = globals.config.SkillsSettings.SkillProgressRate;
pointsToAdd = skillProgressRate * pointsToAdd; pointsToAdd *= skillProgressRate;
} }
profileSkill.Progress += pointsToAdd; profileSkill.Progress += pointsToAdd;

View File

@ -327,7 +327,7 @@ export class RagfairOfferHelper
if (!offer.sellInOnePiece) if (!offer.sellInOnePiece)
{ {
totalItemsCount = offer.items.reduce((sum: number, item) => sum += item.upd.StackObjectsCount, 0); totalItemsCount = offer.items.reduce((sum: number, item) => sum + item.upd.StackObjectsCount, 0);
boughtAmount = offer.sellResult[0].amount; boughtAmount = offer.sellResult[0].amount;
} }
@ -729,6 +729,16 @@ export class RagfairOfferHelper
return true; return true;
} }
public isDisplayableOfferThatNeedsItem(searchRequest: ISearchRequestData, offer: IRagfairOffer): boolean
{
if (offer.requirements.some((requirement) => requirement._tpl === searchRequest.neededSearchId))
{
return true;
}
return false;
}
/** /**
* Does the passed in item have a condition property * Does the passed in item have a condition property
* @param item Item to check * @param item Item to check

View File

@ -573,24 +573,16 @@ export class RepairService
/** /**
* Ensure multiplier is between 1 and 0.01 * Ensure multiplier is between 1 and 0.01
* @param receiveDurabilityMaxPercent Max durabiltiy percent * @param receiveDurabilityMaxPercent Max durability percent
* @param receiveDurabilityPercent current durability percent * @param receiveDurabilityPercent current durability percent
* @returns durability multipler value * @returns durability multiplier value
*/ */
protected getDurabilityMultiplier(receiveDurabilityMaxPercent: number, receiveDurabilityPercent: number): number protected getDurabilityMultiplier(receiveDurabilityMaxPercent: number, receiveDurabilityPercent: number): number
{ {
receiveDurabilityMaxPercent = (receiveDurabilityMaxPercent > 0) ? receiveDurabilityMaxPercent : 0.01; // Ensure the max percent is at least 0.01
const num = receiveDurabilityPercent / receiveDurabilityMaxPercent; const validMaxPercent = Math.max(0.01, receiveDurabilityMaxPercent);
if (num > 1) // Calculate the ratio and constrain it between 0.01 and 1
{ return Math.min(1, Math.max(0.01, receiveDurabilityPercent / validMaxPercent));
return 1.0;
}
if (num < 0.01)
{
return 0.01;
}
return num;
} }
} }

View File

@ -22,9 +22,14 @@ export class MathUtil
*/ */
public arrayCumsum(values: number[]): number[] public arrayCumsum(values: number[]): number[]
{ {
// curried function for cumulative sum: (cum, x) => cum += x const cumsumArray = [];
// and 0 being the initial value for the map let sum = 0;
return values.map(((cum) => (x) => cum += x)(0)); for (let i = 0; i < values.length; i++)
{
sum += values[i];
cumsumArray[i] = sum;
}
return cumsumArray;
} }
/** /**

View File

@ -17,7 +17,8 @@ export class ObjectId
public incGlobalCounter(): number public incGlobalCounter(): number
{ {
return (this.globalCounter = (this.globalCounter + 1) % 0xffffff); this.globalCounter = (this.globalCounter + 1) % 0xffffff;
return this.globalCounter;
} }
public toHexString(byteArray: string | any[] | Buffer): string public toHexString(byteArray: string | any[] | Buffer): string

View File

@ -206,9 +206,9 @@ export class RandomUtil
public getInt(min: number, max: number): number public getInt(min: number, max: number): number
{ {
min = Math.ceil(min); const minimum = Math.ceil(min);
max = Math.floor(max); const maximum = Math.floor(max);
return (max > min) ? Math.floor(Math.random() * (max - min + 1) + min) : min; return (maximum > minimum) ? Math.floor(Math.random() * (maximum - minimum + 1) + minimum) : minimum;
} }
public getIntEx(max: number): number public getIntEx(max: number): number
@ -302,7 +302,7 @@ export class RandomUtil
return this.getFloat(0.01, mean * 2); return this.getFloat(0.01, mean * 2);
} }
return this.getNormallyDistributedRandomNumber(mean, sigma, attempt++); return this.getNormallyDistributedRandomNumber(mean, sigma, attempt + 1);
} }
return valueDrawn; return valueDrawn;
@ -329,15 +329,16 @@ export class RandomUtil
* Draw a random element of the provided list N times to return an array of N random elements * Draw a random element of the provided list N times to return an array of N random elements
* Drawing can be with or without replacement * Drawing can be with or without replacement
* @param {array} list The array we want to draw randomly from * @param {array} list The array we want to draw randomly from
* @param {integer} count The number of times we want to draw * @param {integer} count The number of times we want to draw
* @param {boolean} replacement Draw with or without replacement from the input array(defult true) * @param {boolean} replacement Draw with or without replacement from the input array(default true)
* @return {array} Array consisting of N random elements * @return {array} Array consisting of N random elements
*/ */
public drawRandomFromList<T>(list: Array<T>, count = 1, replacement = true): Array<T> public drawRandomFromList<T>(originalList: Array<T>, count = 1, replacement = true): Array<T>
{ {
let list = originalList;
if (!replacement) if (!replacement)
{ {
list = this.jsonUtil.clone(list); list = this.jsonUtil.clone(originalList);
} }
const results = []; const results = [];

View File

@ -397,7 +397,10 @@ describe("InsuranceController", () =>
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
@ -462,12 +465,18 @@ describe("InsuranceController", () =>
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) =>
{ {
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
}); });
vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments);
@ -526,12 +535,18 @@ describe("InsuranceController", () =>
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) =>
{ {
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
}); });
vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments);
@ -572,11 +587,11 @@ describe("InsuranceController", () =>
"9f8d7880a6e0a47a211ec5d3", "9f8d7880a6e0a47a211ec5d3",
"db2ef9442178910eba985b51", "db2ef9442178910eba985b51",
]; ];
validAttachmentTemplates.forEach((value) => for (const value of validAttachmentTemplates)
{ {
// Verify that each template is present in the array of attachments. // Verify that each template is present in the array of attachments.
expect(gun.some((item) => item._id === value)).toBe(true); expect(gun.some((item) => item._id === value)).toBe(true);
}); }
}); });
it("should ignore gun accessories that cannot be modified in-raid", () => it("should ignore gun accessories that cannot be modified in-raid", () =>
@ -602,10 +617,11 @@ describe("InsuranceController", () =>
"402b4086535a50ef7d9cef88", "402b4086535a50ef7d9cef88",
"566335b3df586f34b47f5e35", "566335b3df586f34b47f5e35",
]; ];
invalidAttachmentTemplates.forEach((value) => for (const value of invalidAttachmentTemplates)
{ {
// Verify that each template is not present in the array of attachments.
expect(gun.every((item) => item._id !== value)).toBe(true); expect(gun.every((item) => item._id !== value)).toBe(true);
}); }
}); });
it("should correctly map helmet to all of its attachments", () => it("should correctly map helmet to all of its attachments", () =>
@ -632,11 +648,11 @@ describe("InsuranceController", () =>
"ac134d7cf6c9d8e25edd0015", "ac134d7cf6c9d8e25edd0015",
"22274b895ecc80d51c3cba1c", "22274b895ecc80d51c3cba1c",
]; ];
validAttachmentTemplates.forEach((value) => for (const value of validAttachmentTemplates)
{ {
// Verify that each template is present in the array of attachments. // Verify that each template is present in the array of attachments.
expect(gun.some((item) => item._id === value)).toBe(true); expect(gun.some((item) => item._id === value)).toBe(true);
}); }
}); });
it("should correctly map gun to all of its attachments when gun is within a container", () => it("should correctly map gun to all of its attachments when gun is within a container", () =>
@ -900,10 +916,10 @@ describe("InsuranceController", () =>
// Verify that the attachments with null maxPrice are at the bottom of the list // Verify that the attachments with null maxPrice are at the bottom of the list
const nullPriceAttachments = sortedAttachments.slice(-2); const nullPriceAttachments = sortedAttachments.slice(-2);
nullPriceAttachments.forEach((attachment) => for (const attachment of nullPriceAttachments)
{ {
expect(attachment.maxPrice).toBeNull(); expect(attachment.maxPrice).toBeNull();
}); }
// Verify that the rest of the attachments are sorted by maxPrice in descending order // Verify that the rest of the attachments are sorted by maxPrice in descending order
for (let i = 1; i < sortedAttachments.length - 2; i++) for (let i = 1; i < sortedAttachments.length - 2; i++)
@ -1078,10 +1094,10 @@ describe("InsuranceController", () =>
insuranceController.removeItemsFromInsurance(insured, toDelete); insuranceController.removeItemsFromInsurance(insured, toDelete);
// Ensure that the items in the toDelete set are not present in the insured items array. // Ensure that the items in the toDelete set are not present in the insured items array.
toDelete.forEach((toDeleteId) => for (const toDeleteId of toDelete)
{ {
expect(insured.items.some((item) => item._id === toDeleteId)).toBe(false); expect(insured.items.some((item) => item._id === toDeleteId)).toBe(false);
}); }
}); });
it("should not remove any items if toDelete set is empty", () => it("should not remove any items if toDelete set is empty", () =>
@ -1102,7 +1118,10 @@ describe("InsuranceController", () =>
const insured = insuranceFixture[0]; const insured = insuranceFixture[0];
const originalCount = insured.items.length; const originalCount = insured.items.length;
const toDelete = new Set<string>(); const toDelete = new Set<string>();
insured.items.forEach((item) => toDelete.add(item._id)); for (const item of insured.items)
{
toDelete.add(item._id);
}
// All of the items should be added to the toDelete set. // All of the items should be added to the toDelete set.
expect(originalCount).toBe(toDelete.size); expect(originalCount).toBe(toDelete.size);