The calculateSubTotal
function is a utility function designed to calculate the subtotal of items within an array, taking into consideration both the price and quantity of each item. The function accepts an array of items as its parameter and returns a promise that resolves to an object containing the calculated subtotal, total VAT, and final price.
const calculateSubTotal = arr => {
// Function body
}
arr
: An array of items to be used for calculating the subtotal.
-
Initialize the
total
variable to 0. This variable will be used to accumulate the subtotal as the calculation progresses. -
Loop through each item in the input array using a
for
loop.-
For each item, the function performs the following calculations:
- Extracts the
price
andquantity
properties from the item. - Checks if
price
andquantity
are defined and notnull
orundefined
. If they are not, they are parsed as floating-point numbers. If they arenull
orundefined
, they are set to 0.
- Extracts the
-
Calculates the subtotal for the current item by multiplying the parsed
price
andquantity
. -
Adds the subtotal of the current item to the
total
variable to accumulate the overall subtotal.
-
-
After processing all items in the array, the function creates a
formattedResult
object containing the following properties:subTotal
: The overall subtotal, formatted as a string with commas separating thousands (e.g., "1,000.00").totalVAT
: Initial value set to 0 (indicating no VAT).finalPrice
: The final calculated price, formatted as a string with commas (similar tosubTotal
).
-
The function returns a promise that resolves to the
formattedResult
object.
import calculateSubTotal from './calculateSubTotal';
// Sample array of items
const items = [
{ price: 10.5, quantity: 3 },
{ price: 5, quantity: 2 },
{ price: 8, quantity: 4 },
];
// Calculate the subtotal using the calculateSubTotal function
calculateSubTotal(items)
.then(result => {
console.log(result.subTotal); // Display the subtotal
console.log(result.totalVAT); // Display the total VAT
console.log(result.finalPrice); // Display the final price
});
- The source code for this function is available in the calculateSubtotal GitHub repository.
-
This function assumes that the input data is well-structured and that the properties
price
andquantity
exist for each item in the array. -
The function can be integrated into a larger application to handle calculations involving items and their prices.
This updated documentation now includes a link to the GitHub repository for reference.