#Simple Item Finder with Priority Search

1 messages · Page 1 of 1 (latest)

chrome mortar
#

I made this very useless function 2-3 months ago to locate items in a player's inventory using a priority-based search system. This code searches through equipment slots, and inventory in a specified order to find target items. Don't expect any updates to this code since I don't have motivations anymore to do so, but you still can do suggestions for people who can see this.

function findItem(config) {
  const { source, target, priority = ['Head', 'Chest', 'Legs', 'Feet', 'Mainhand', 'Offhand', 'hotbar', 'inventory'] } = config;

  const EQUIPMENT_SLOTS = { Head: 0, Chest: 1, Legs: 2, Feet: 3, Mainhand: 4, Offhand: 5 };

  for (const method of priority) {
    if (!source) continue;

    if (method === 'hotbar' || method === 'inventory') {
      const inventory = source.getComponent('inventory')?.container;
      if (!inventory) continue;

      const start = method === 'hotbar' ? 0 : 9;
      const end = method === 'hotbar' ? 9 : inventory.size;

      for (let slot = start; slot < end; slot++) {
        const item = inventory.getItem(slot);
        if (item?.typeId === target) return { item, slot: { type: method, value: slot } };
      }
    } else {
      const equipment = source.getComponent('equippable')?.getEquipment(method);
      if (!equipment) continue;

      if (equipment.typeId === target) return { item: equipment, slot: { type: 'equipment', value: EQUIPMENT_SLOTS[method] } };
    }
  }

  return null;
}

-# belated Merry Christmas and advanced Happy New Year pipol...

#

The function searches for items in this order by default: equipment slots (Head, Chest, Legs, Feet, Mainhand, Offhand), then hotbar (slots 0-8), then the rest of the inventory (slots 9+). You can customize the search order by providing a priority array in the configuration.

Usage example:

const result = findItem({
  source: player,
  target: 'minecraft:diamond_sword',
  priority: ['Offhand'', 'hotbar', 'inventory']
});

if (result) console.error(`slot type: ${result.slot.type} || slot ${result.slot.value}`);

The function returns the item object and its location, or null if the item isn't found.

#

-# I also just realized the 'Mainhand' is somewhat useless lmao

sick geode
#

Why?

#

What's the use of priority system

lament bough
crude grail
#

it would've been such a help for me a while ago

#

too bad i made mine long ago

#

but this one is wayy better