Build an Inventory Management Program - Build an Inventory Management Program

Tell us what’s happening:

Hi! I’m passing every test except #15. Based on my testing, it seems to be removing the product when the new quantity is zero. However, I can’t seem to figure out why it’s not passing the test. Any help is appreciated!

Your code so far

let inventory = [];

function findProductIndex (name) {
  name = name.toLowerCase();
  
  for (let i = 0; i < inventory.length; i++) {
    if (inventory[i]["name"] === name) {
      return i;
    }
  }

  return -1;
}

function addProduct (product) {  
  product["name"] = product["name"].toLowerCase();
  const productIndex = findProductIndex(product.name);
  
  if (productIndex != -1) {
    inventory[productIndex]["quantity"] += product["quantity"];
    console.log(`${product.name} quantity updated`);
  } else {    
    inventory.push(product);
    console.log(`${product.name} added to inventory`);
  }
}

function removeProduct (name, quantity) {
  name = name.toLowerCase();
  
  const productIndex = findProductIndex(name);
  
  if (productIndex === -1) {
    console.log(`${name} not found`);
  } else {
    let newQuantity = inventory[productIndex]["quantity"] -= quantity;

    if (newQuantity > 0) {
      console.log(`Remaining ${name} pieces: ${newQuantity}`);
    } else if (newQuantity < 0) {
      inventory[productIndex]["quantity"] += quantity;
      console.log(`Not enough ${name} available, remaining pieces: ${inventory[productIndex]["quantity"]}`);
    } else if (newQuantity === 0) {
      delete inventory[productIndex];
    }
  }
}

//Testing area

let newObj = {
  name: "FLOUR",
  quantity: 5
}



addProduct(newObj);
addProduct(newObj);
removeProduct("flour", 10); 
console.log(inventory);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0

Challenge Information:

Build an Inventory Management Program - Build an Inventory Management Program

when you use the delete operator to remove the item from inventory it acts somewhat like this -

const arr = ["a", "b", "c", "d", "e"];

console.log(arr); //["a", "b", "c", "d", "e"];
console.log(arr.length); //5

delete arr[1];
console.log(arr); //["a", <empty>, "c", "d", "e"];
console.log(arr.length); //5

as you can see it does not change the arr.length, it replaces the element with an empty hole.

can you think of some other method to remove the required item from inventory?

3 Likes

The splice() method worked! Thanks for the help.

1 Like