diff --git a/src/Inventory.ts b/src/Inventory.ts index 0091954..0043cdc 100644 --- a/src/Inventory.ts +++ b/src/Inventory.ts @@ -6,17 +6,13 @@ export default class Inventory implements HasData { readonly size: number readonly columns: number - private slots: ItemStack[] + private slots: (ItemStack | undefined)[] constructor(size: number, columns: number = 9, data: InventoryData = []) { this.size = size this.columns = columns this.slots = [] - // fill with air (default) - for (let i = 0; i < this.size; i++) this.slots[i] = new ItemStack(new Item("tiny:air"), 1) - - // fill slots with data data.forEach(stack => { this.slots[stack.slot] = new ItemStack(stack.item.id, stack.amount) @@ -28,21 +24,21 @@ export default class Inventory implements HasData { else throw new Error(`IndexOutOfBounds: Inventory slot ${index} (0..${this.size})`) } - get(index: number) { - if (index >= 0 && index < this.size) return this.slots[index] + get(index: number): ItemStack { + if (index >= 0 && index < this.size) return this.slots[index] ?? new ItemStack("tiny:air") throw new Error(`IndexOutOfBounds: Inventory slot ${index} (0..${this.size})`) } each(cb: (value: ItemStack, index: number) => void) { - return this.slots.forEach(cb) + return this.slots.forEach((stack, index) => cb(stack || new ItemStack("tiny:air"), index)) } addItems(stack: ItemStack): ItemStack | null { let { amount } = stack - for (const i in this.slots) { - const slot = this.slots[i] + for (const i of this.slots.keys()) { + const slot = this.get(i) if (amount <= 0) break @@ -67,22 +63,23 @@ export default class Inventory implements HasData { } find(item: Item): number { - for (const i in this.slots) if (this.slots[i].match(item)) return Number(i) + for (const i of this.slots.keys()) if (this.get(i).match(item)) return Number(i) return -1 } emptySlots(): number { let count = 0 - for (const slot of this.slots) { - if (slot.item.id.matches("tiny:air")) count++ - } + + this.each(stack => { + if (stack.item.id.matches("tiny:air")) count++ + }) return count } firstEmptySlot(): number { - for (const i in this.slots) if (this.slots[i].item.id.matches("tiny:air")) return Number(i) + for (const i of this.slots.keys()) if (this.get(i).item.id.matches("tiny:air")) return Number(i) return -1 } @@ -90,7 +87,7 @@ export default class Inventory implements HasData { getData() { const arr: (ReturnType & {slot: number})[] = [] - this.slots.forEach((slot, index) => { + this.each((slot, index) => { if (slot.item.id.matches("tiny:air")) return arr.push({ ...slot.getData(), slot: index })