Well, the title explains.
-
Failed:3.
findProductIndex("flour")should return the index of the object havingnameequal to"flour"inside theinventoryarray. -
Failed:4.
findProductIndex("FloUr")should return the index of the object havingnameequal to"flour"inside theinventoryarray. -
Failed:7.
addProduct({name: "FLOUR", quantity: 5})should add5toquantityvalue of the object havingnameequal to"flour"in theinventoryarray. -
Failed:8.
addProduct({name: "FLOUR", quantity: 5})should logflour quantity updatedwhen an object havingnameequal to"flour"is found in theinventoryarray. -
13.
removeProduct("FLOUR", 5)should subtract5from thequantityvalue of the object havingnameequal to"flour"inside theinventoryarray. -
Failed:14.
removeProduct("FLOUR", 5)should logRemaining flour pieces: 15to the console, wheninventoryis equal to[{name: "flour", quantity: 20}, {name: "rice", quantity: 5}]. -
Failed:15. If the
quantityafter the subtraction is zero,removeProductshould remove the product object from the inventory. -
Failed:16.
removeProduct("FLOUR", 10)should logNot enough flour available, remaining pieces: 5wheninventoryis equal to[{name: "flour", quantity: 5}, {name: "rice", quantity: 5}].
It seems I can’t get these tests to pass.
Here’s the code:
let inventory = []
function findProductIndex(str) {
if (inventory.length == 0) {
return -1
} else {
str = str.toLowerCase()
for (let i = 0; i <= inventory.length; i++) {
if (inventory[i].name == str) {
return i
} else {
return -1
}
}
}
}
function addProduct(obj) {
let productIndex = findProductIndex(obj.name)
if (productIndex !== -1) {
let product = inventory[productIndex]
product.quantity += obj.quantity
obj.name = obj.name.toLowerCase()
console.log(`${obj.name} quantity updated`)
} else {
obj.name = obj.name.toLowerCase()
inventory.push(obj)
console.log(`${obj.name} added to inventory`)
}
}
function removeProduct(str, int) {
let productIndex = findProductIndex(str)
str = str.toLowerCase()
if (productIndex == -1) {
console.log(`${str} not found`)
} else {
let product = inventory[productIndex]
if (product.quantity >= int) {
product.quantity -= int
console.log(`Remaining ${str} pieces: ${product.quantity}`)
if (product.quantity == 0) {
inventory.splice(productIndex, 1)
}
} else {
console.log(`Not enough ${str} available, remaining pieces: ${product.quantity}`)
}
}
}
