I was taking an online assessment, and I cannot figure out why my original solution in JS was not working. My first solution is contained in the top two function calls. No matter what, it returned an empty object {}. When I copy and pasted the function body from findOrderQuantity into allCandyOrders, it worked just fine.
function findOrderQuantity(candyObject) {
if (candyObject.inStock < candyObject.weeklyAverage) {
return 2 * candyObject.weeklyAverage;
} else {
return 0;
}
return 0;
}
function allCandyOrders(inventory) {
// this function fails, and always returns {}
let orderSet = {};
let quantity = 0;
let name = '';
for (let i = 0; i < inventory.lengh; i++) {
// compute how many to order
quantity = findOrderQuantity(inventory[i]);
// add candy to object
// inventory[i].candy is a string containing a candyName
name = inventory[i].candy;
orderSet[name] = quantity;
}
return orderSet;
}
Working code
function allCandyOrders(inventory) {
// this function works properly.
let orderSet = {};
let value = 0;
let candyObject = inventory[0];
for (let i = 0; i < inventory.length; i++) {
candyObject = inventory[i];
if (candyObject.inStock < candyObject.weeklyAverage) {
value = 2 * candyObject.weeklyAverage;
} else {
value = 0;
}
orderSet[inventory[i].candy] = value;
}
return orderSet;
}
I had originally tried to dynamically create the orderSet object using Object.assign, but it didn't work either. Inventory is an array containing candy objects, which has attributes [candy (string), inStock (int), weeklyAverage (int)]. I'm assuming it's some kind of scope issue, but I can't seem to figure it out. Otherwise, I must be missing something about how JS works. Thank you in advance for your help.
Best,
Brian