I am trying to generate an invoice based on the array of orders and outlets, to do that I have to go through outlets array and get the comission as well as some other information and based on it I loop through the orders array in order to do the necessary calculations; however it seems that I have a logical issue as I am trying to get the values needed on outlets array which has a length of 2 and the length of orders array is 3 so the orders array is always not fully executed but stops at the second index.
The question : What should I do in order to list/calculate the final invoice for each store (id) ?
Live code to debug : https://playcode.io/597316/
Here is the code :
var finalAmount = 0;
var itemsProcessed = 0;
async function dodo() {
try {
const orders = {
Items: [ {
outletId: 2,
percentage: 20,
amountUsed: 0,
amountEntered: 100,
},
{
outletId: 2,
percentage: 20,
amountUsed: 0,
amountEntered: 100,
},
{
outletId: 1,
percentage: 10,
amountUsed: 0,
amountEntered: 300,
}],
Count: 1
};
let outlets = {
Items: [
{
id: 1,
name: 'Test Shop',
percentage: 10,
commission: 5,
},
{
id: 2,
name: 'Test 2 Shop',
percentage: 20,
commission: 5,
}
],
Count: 2,
ScannedCount: 2
};
for (var i = 0; i < outlets.Items.length; i++) {
if (orders.Count > 0) {
orders.Items.forEach(order => {
finalAmount += parseFloat((order.amountEntered - (order.amountEntered * (outlets.Items[i].commission + outlets.Items[i].percentage) / 100)).toFixed(2));
},itemsProcessed++);
}
//itemsProcessed seems to stop at 2 because outlets.Items.length = 2
//Never goes inside because orders.Items.length > itemsProcessed
if (finalAmount > 0 && itemsProcessed === orders.Items.length) {
//Create Invoice
console.log('Generate invoice with an amount of ', finalAmount);
finalAmount = 0;
}
}
} catch (err) {
console.log('Error ', err);
}
}
dodo();
itemsProcessed++is executed in the loop that iterates overoutlets.Items, not insideorders.Items.forEach. So yes, it will never be> 2. Butorders.Items.forEachwill still iterate over all elements in that array.