Created
October 3, 2015 18:59
-
-
Save tomauty/ac1f775b4d24c69a1c39 to your computer and use it in GitHub Desktop.
inventory wip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
const _internal = new WeakMap(); | |
class Inventory { | |
/** | |
* | |
* @constructs Inventory | |
* @classdesc An inventory is a collection of Item objects, belonging to an Entity, with a capacity | |
* | |
* @param {Entity} belongsTo - The entity that has this inventory | |
* @param {Item[]} items - The items contained in the inventory | |
* @param {number} capacity - The amount of items this inventory can hold | |
* | |
* @returns {Inventory} - instance of Inventory | |
*/ | |
constructor(belongsTo, items, capacity) { | |
_internal.set(this, { | |
belongsTo, | |
items: items || [], | |
capacity: capacity || 10 | |
}) | |
} | |
/** | |
* Get all items in inventory | |
* @method Inventory#getItems | |
* @returns {Item[]} - All items | |
*/ | |
getItems() { | |
return _internal.get(this).items; | |
} | |
/** | |
* Get the capacity of the inventory | |
* @method Inventory#getCapacity | |
* @returns {number} capacity - The total capacity of the inventory | |
*/ | |
getCapacity() { | |
return _internal.get(this).capacity; | |
} | |
/** | |
* Check if an item is in this inventory | |
* @method Inventory#existsInInventory | |
* @param {Item} item - The item to check for | |
* @returns {Item|boolean} - Item -- contained, false -- not contained | |
*/ | |
existsInInventory(item) { | |
const found = _.find(this.getItems(), (inventoryItem) => { | |
return inventoryItem.getId() === item.getId(); | |
}); | |
return found || false; | |
} | |
/** | |
* Add an item to the inventory. Returns false if no capacity | |
* @method Inventory#addItem | |
* @param {Item} item - The item to add, stacking if necessary | |
* @returns {Inventory|boolean} - The inventory instance OR could not add | |
*/ | |
addItem(item) { | |
const existingItem = this.existsInInventory(item); | |
if (existingItem) { | |
existingItem.setCount(existingItem.getCount() + 1); | |
return this; | |
} | |
if (this.getCapacity() === this.getItems().length) { | |
return false; | |
} | |
_internal.get(this).items.push(item); | |
return this; | |
} | |
} | |
module.exports = Inventory; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment