Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class InventoryManager {
- constructor(capacity) {
- this.capacity = capacity;
- this.items = [];
- this.outOfStock = [];
- }
- addItem(itemName, quantity) {
- if (quantity <= 0) {
- throw new Error("Quantity must be greater than zero.");
- }
- if (this.items.length >= this.capacity) {
- throw new Error("The inventory is already full.");
- }
- let index = this.items.findIndex(items => items.name === itemName);
- if (index === -1) {
- let item = {
- itemName,
- quantity,
- }
- this.items.push(item);
- } else {
- this.items[index].quantity += quantity;
- }
- return `Added ${quantity} ${itemName}(s) to the inventory.`;
- }
- sellItem(itemName, quantity) {
- if (quantity <= 0) {
- throw new Error("Quantity must be greater than zero.");
- }
- let index = this.items.findIndex(items => items.itemName === itemName);
- if (index === -1) {
- throw new Error(`The item ${itemName} is not available in the inventory.`)
- }
- let availableQuantity = this.items[index].quantity;
- if (quantity > availableQuantity) {
- throw new Error(`Not enough ${itemName}(s) in stock.`);
- }
- this.items[index].quantity -= quantity;
- if (this.items[index].quantity === 0) {
- this.outOfStock.push(this.items[index].itemName);
- this.items.splice(index, 1);
- }
- return `Sold ${quantity} ${itemName}(s) from the inventory.`;
- }
- restockItem(itemName, quantity) {
- if (quantity <= 0) {
- throw new Error("Quantity must be greater than zero.");
- }
- let index = this.items.findIndex(items => items.itemName === itemName);
- if (index !== -1) {
- this.items[index].quantity += quantity;
- } else {
- let itemToAdd = {
- itemName,
- quantity
- };
- this.items.push(itemToAdd);
- if (this.outOfStock.includes(itemName)) {
- let indexR = this.outOfStock.indexOf(itemName);
- this.outOfStock.splice(indexR, 1);
- }
- }
- return `Restocked ${quantity} ${itemName}(s) in the inventory.`
- }
- getInventorySummary() {
- let result = 'Current Inventory:';
- for (const item of this.items) {
- result += `\n${item.itemName}: ${item.quantity}`;
- }
- if (this.outOfStock.length !== 0) {
- result += `\nOut of Stock: ${this.outOfStock.join(',')}`;
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment