4 Extracting calculations from actions

In this chapter
- Observe how information enters and leaves a function.
- Discover functional techniques to make code more testable and reusable.
- Learn how to extract calculations from actions.
In this chapter, we’re going to do a lot of refactoring. We’re going to look at an existing piece of software, add some features, and then refactor calculations out of the actions. This improves the reuse and testability of the code.
Welcome to MegaMart.com!
Where your shopping cart is always full
MegaMart is an online store. One of its key features, and how it stays competitive, is that the shopping cart always shows you the total cost of its contents—even while you’re shopping.

MegaMart reveals its secret code to you
No NDA required
var shopping_cart = []; #1 var shopping_cart_total = 0; function add_item_to_cart(name, price) { shopping_cart.push({ #2 name: name, price: price }); calc_cart_total(); #3 } function calc_cart_total() { shopping_cart_total = 0; for(var i = 0; i < shopping_cart.length; i++) { var item = shopping_cart[i]; #4 shopping_cart_total += item.price; } set_cart_total_dom(); #5 }
The final line updates the document object model (DOM), which is how web programmers modify a web page in the browser.
Vocab time
The document object model (DOM) is the in-memory representation of an HTML page in a browser.
Calculating free shipping
Your new assignment