package inventoryapi import ( "context" inventory "crossnokaye-interview-assignment/services/inventory/gen/inventory" "errors" "log" ) // inventory service example implementation. // The example methods log the requests and return zero values. type inventorysrvc struct { logger *log.Logger inventories map[int]*[]int //key = characterId, value = array of itemIds } // NewInventory returns the inventory service implementation. func NewInventory(logger *log.Logger) inventory.Service { inventoryMap := make(map[int]*[]int) return &inventorysrvc{logger, inventoryMap} } // AddItem implements addItem. func (s *inventorysrvc) AddItem(ctx context.Context, p *inventory.InventoryRecord) (err error) { s.logger.Print("inventory.addItem") itemList := s.inventories[*p.CharacterID] if itemList == nil { itemList = s.initCharacterInventory(p.CharacterID) } newItemList := append(*itemList, *p.ItemID) s.inventories[*p.CharacterID] = &newItemList return } // RemoveItem implements removeItem. func (s *inventorysrvc) RemoveItem(ctx context.Context, p *inventory.InventoryRecord) (err error) { s.logger.Print("inventory.removeItem") itemList := s.inventories[*p.CharacterID] if itemList == nil { s.logger.Printf("inventory for character with id %d not found", p.CharacterID) return errors.New("item not found") } idx := indexOf(*p.ItemID, *itemList) if idx != -1 { newItemList := remove(*itemList, idx) s.inventories[*p.CharacterID] = &newItemList } else { s.logger.Printf("character with id %d does not have item %d in inventory", &p.CharacterID, &p.ItemID) return errors.New("item not found for character") } return } func (s *inventorysrvc) ListInventory(ctx context.Context, payload *inventory.ListInventoryPayload) (res []int, err error) { res = *s.inventories[*payload.CharacterID] return } func (s *inventorysrvc) initCharacterInventory(characterId *int) (itemList *[]int) { list := make([]int, 0) itemList = &list s.inventories[*characterId] = &list return } func indexOf(element int, data []int) int { for k, v := range data { if element == v { return k } } return -1 //not found. } func remove(s []int, i int) []int { s[i] = s[len(s)-1] return s[:len(s)-1] }