Server/project/src/services/RagfairCategoriesService.ts

97 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-03-03 16:23:46 +01:00
import { inject, injectable } from "tsyringe";
import { IRagfairOffer } from "@spt-aki/models/eft/ragfair/IRagfairOffer";
import { ILogger } from "@spt-aki/models/spt/utils/ILogger";
2023-03-03 16:23:46 +01:00
@injectable()
export class RagfairCategoriesService
{
protected categories: Record<string, number> = {};
constructor(@inject("WinstonLogger") protected logger: ILogger)
{}
2023-03-03 16:23:46 +01:00
/**
* Get all flea categories and their count of offers
* @returns item categories and count
*/
public getAllCategories(): Record<string, number>
2023-03-03 16:23:46 +01:00
{
return this.categories;
}
/**
* With the supplied items, get custom categories
* @returns a custom list of categories
*/
public getBespokeCategories(offers: IRagfairOffer[]): Record<string, number>
2023-03-03 16:23:46 +01:00
{
return this.processOffersIntoCategories(offers);
2023-03-03 16:23:46 +01:00
}
/**
* Take an array of ragfair offers and create a dictionary of items with thier corrisponding offer count
* @param offers ragfair offers
* @returns categories and count
*/
protected processOffersIntoCategories(offers: IRagfairOffer[]): Record<string, number>
2023-03-03 16:23:46 +01:00
{
const result = {};
for (const offer of offers)
{
this.addOrIncrementCategory(offer, result);
}
return result;
}
/**
* Increment or decrement a category array
2023-04-24 15:19:42 +02:00
* @param offer Offer to process
* @param categories Categories to update
* @param increment (Optional) Should item be incremented or decremented
2023-03-03 16:23:46 +01:00
*/
protected addOrIncrementCategory(offer: IRagfairOffer, categories: Record<string, number>, increment = true): void
2023-03-03 16:23:46 +01:00
{
const itemId = offer.items[0]._tpl;
if (increment)
{
categories[itemId] = categories[itemId] ? categories[itemId] + 1 : 1;
2023-03-03 16:23:46 +01:00
}
else
{
// No category, no work to do
if (categories[itemId])
{
categories[itemId]--;
2023-04-24 15:19:42 +02:00
// Remove category entirely as its 0 or less
if (categories[itemId] < 1)
{
delete categories[itemId];
}
2023-03-03 16:23:46 +01:00
}
}
}
/**
* Increase category count by 1
* @param offer
2023-03-03 16:23:46 +01:00
*/
public incrementCategory(offer: IRagfairOffer): void
{
this.addOrIncrementCategory(offer, this.categories);
this.categories[offer.items[0]._tpl]++;
}
/**
* Reduce category count by 1
* @param offer
2023-03-03 16:23:46 +01:00
*/
public decrementCategory(offer: IRagfairOffer): void
{
this.addOrIncrementCategory(offer, this.categories, false);
this.categories[offer.items[0]._tpl]--;
}
}