6/16 lessons38%

Example of Pure Functions

Pure functions are more than theoretical constructs—they’re practical tools that help build reliable, reusable components. In this lesson, we’ll create a feature resembling a micro app: a shopping cart system that calculates the total price of items. This example will evolve in future chapters as we incorporate more functional programming principles.

Shopping Cart Calculator

We’ll build a pure function that:

  1. 1
    Accepts a list of cart items as input.
  2. 2
    Returns the total price without altering the original data.

Define the Input Structure

javascript
1
2
3
4
5
          const cart = [
  { name: "Laptop", price: 1200, quantity: 1 },
  { name: "Phone", price: 800, quantity: 2 },
  { name: "Headphones", price: 150, quantity: 3 },
];
        

Create a Pure Function

  1. 1
    Take the cart array as input.
  2. 2
    Use reduce to compute the total price.
  3. 3
    Return the total without modifying the original cart.
javascript
1
2
3
4
5
6
7
8
          function calculateTotal(cart) {
  return cart.reduce((total, item) => total + item.price * item.quantity, 0);
}

// Testing the function
const total = calculateTotal(cart);
console.log(total); // 2950
console.log(cart); // Original cart remains unchanged
        

Tax Calculation

Add another pure function to calculate the total price, including tax.

javascript
1
2
3
4
5
6
7
          function applyTax(total, taxRate) {
  return total + total * taxRate;
}

// Testing the function
const totalWithTax = applyTax(total, 0.1); // Assuming 10% tax
console.log(totalWithTax); // 3245
        

Formatting Output

A utility function to format the total as a string with a currency symbol.

javascript
1
2
3
4
5
6
          function formatCurrency(amount, currencySymbol = "$") {
  return `${currencySymbol}${amount.toFixed(2)}`;
}

// Testing the function
console.log(formatCurrency(totalWithTax)); // $3245.00
        

Collecting Functions

Let’s put these functions together to create a complete workflow:

  1. 1
    Calculate the total.
  2. 2
    Apply tax.
  3. 3
    Format the final output.
javascript
1
2
3
4
5
          const cartTotal = calculateTotal(cart);
const totalWithTaxApplied = applyTax(cartTotal, 0.1);
const formattedTotal = formatCurrency(totalWithTaxApplied);

console.log(formattedTotal); // $3245.00
        

Why Is This Pure?

  1. 1
    Deterministic Behavior: Each function returns the same output for the same input.
  2. 2
    No Side Effects: The original cart array remains unaltered.
  3. 3
    Reusable Components: Functions like applyTax and formatCurrency can be used elsewhere in the app.

Next Steps

In future lessons, we can enhance this feature by:

  • Incorporating higher-order functions to make the tax application process more dynamic.
  • Adding immutability to ensure the cart remains untouched during updates.
  • Applying function composition to streamline calculations.