The Magic Potion Shop

The Magic Potion Shop

You are running a potion shop, and each day you restock the potions. You need to calculate the total price of the potions based on different conditions, while ensuring that the calculations remain accurate and efficient.

Task:

  1. Write a function calculateTotalPrice that accepts an array of potion objects. Each object contains:
  2. You also have a special condition: If the potion name is "Magic Elixir", you give a 10% discount on the total price of that specific potion.
  3. There are two pricing rules:

Constraints:

  • You cannot use global variables.
  • Ensure that each discount calculation only affects the potion it applies to and doesn't interfere with other potion types.
  • Use appropriate variable scoping (avoid hoisting issues).

Example Input:

calculateTotalPrice(potions);
// Expected output: 5050

// Explanation:
// Healing Potion total price: 50 * 5 = 250
// Mana Potion total price with discount: 100 * 15 * 0.95 = 1425
// Magic Elixir total price with two discounts: 200 * 20 * 0.9 * 0.95 = 3420
// Total = 250 + 1425 + 3420 = 5050        

Solution Skeleton (TypeScript):

interface Potion {
  name: string;
  price: number;
  quantity: number;
}

function calculateTotalPrice(potions: Potion[]): number {
  let totalPrice = 0;

  potions.forEach(potion => {
    let price = potion.price * potion.quantity;

    // Apply discount if the quantity is greater than 10
    if (potion.quantity > 10) {
      price *= 0.95;
    }

    // Apply Magic Elixir discount
    if (potion.name === "Magic Elixir") {
      price *= 0.9;
    }

    totalPrice += price;
  });

  return totalPrice;
}

// Example usage
const potions: Potion[] = [
  { name: "Healing Potion", price: 50, quantity: 5 },
  { name: "Mana Potion", price: 100, quantity: 15 },
  { name: "Magic Elixir", price: 200, quantity: 20 }
];

console.log(calculateTotalPrice(potions)); // Output: 5050        

Concepts Covered:

  • Proper use of variable scoping inside loops.
  • Basic arithmetic operations and percentage calculations.
  • Conditional logic for applying different discounts.
  • Working with objects and arrays.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics