Efficiently Calculating Total Cost: A JavaScript Function

Imagine you are building an e-commerce application that needs to calculate the total cost of items in a shopping cart. The prices and quantities of the items are stored in two separate arrays. You need to write a function that takes these two arrays as input and returns the total cost.

The Solution

The calculateTotalCost function is a simple and efficient solution to this problem. Here is the code:

JavaScriptfunction calculateTotalCost(prices, quantities) {
    // Initialize total cost to 0
    let totalCost = 0;
    
    // Loop through prices and quantities arrays
    for (let i = 0; i < prices.length; i++) {
        // For each item, multiply the price by the quantity and add to total cost
        totalCost += prices[i] * quantities[i];
    }
    
    // Return the total cost
    return totalCost;
}

How it Works

The function works by iterating through the prices and quantities arrays simultaneously, using a for loop. For each item, it multiplies the price by the quantity and adds the result to the totalCost variable. Finally, it returns the totalCost.

man monitoring laptops and using surveillance equipment - hack squat stock pictures, royalty-free photos & images

Example Usage

To demonstrate the usage of the calculateTotalCost function, let’s consider an example. Suppose we have the following prices and quantities:

JavaScriptconst prices = [10, 20, 30];
const quantities = [2, 3, 1];

We can call the calculateTotalCost function with these arrays as arguments:

JavaScriptconsole.log(calculateTotalCost(prices, quantities));  // Output: 110

The output will be 110, which is the total cost of the items.

Advantages

The calculateTotalCost function has several advantages:

  • It is simple and easy to understand.
  • It is efficient, with a time complexity of O(n), where n is the length of the input arrays.
  • It is reusable and can be used in various contexts where you need to calculate the total cost of items.

Conclusion

The calculateTotalCost function is a simple yet effective solution for calculating the total cost of items based on their prices and quantities. Its simplicity, efficiency, and reusability make it a valuable tool for any developer working on an e-commerce application or any other project that requires similar calculations.

CLICK HERE FOR MORE BLOG POSTS

Leave a Comment