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:
- 1Accepts a list of cart items as input.
- 2Returns 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
- 1Take the cart array as input.
- 2Use
reduce
to compute the total price. - 3Return 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:
- 1Calculate the total.
- 2Apply tax.
- 3Format 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?
- 1Deterministic Behavior: Each function returns the same output for the same input.
- 2No Side Effects: The original cart array remains unaltered.
- 3Reusable Components: Functions like
applyTax
andformatCurrency
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.