Exercise #08 - ShoppingCart V2

Continues from Exercise #07.
Items can now be added multiple times. If the item is in the cart already, add the existing quantity to the new item's quantity.

Expose the same two routes, but return items ordered by quantity, from highest to lowest.

Use the Map k v type from the Data.Map.Strict module (containers package) to store items in the cart. You'll need the lookup and insert functions.

The cart starts empty. Note how the order of the returned items changes as more items are added.

    GET /cart
    >>> expected []

    POST /cart
    { "model": "first thing", "quantity": 2 }

    GET /cart
    >>> expected
      [
        { "model": "first thing", "quantity": 2 }
      ]

    POST /cart
    { "model": "another thing", "quantity": 30 }

    GET /cart
    >>> expected
      [
        { "model": "another thing", "quantity": 30 },
        { "model": "first thing", "quantity": 2 }
      ]

    POST /cart
    { "model": "first thing", "quantity": 45 }

    GET /cart
    >>> expected
      [
        { "model": "first thing", "quantity": 47 },
        { "model": "another thing", "quantity": 30 }
      ]

  

It looks like your server isn't up. This page expects your Haskell application to be listineing on http://localhost:7879.
If you're unsure on how to proceed, read more on how to setup your Local dev environment to complete the exercises.

Refresh the page to run the tests again.

Reference node.js implementation

          
const app = require("express")()
const bodyParser = require("body-parser")

app.use(bodyParser.json())

// Mutable state!
// Items are indexed by "model"
let currentCart = {}

app.post("/cart", (req, res) => {
  const item = req.body

  if (item.model && item.quantity)
  {
    const existingQuantity = currentCart[item.model] ? currentCart[item.model].quantity : 0
    item.quantity = existingQuantity + item.quantity
    currentCart[item.model] = item
    res.send("ok")
  }
  else {
    throw new Error("Not a valid item")
  }
})

app.get("/cart", (req, res) => {
  const items = Object.values(currentCart)
  // Items should be sorted by quantity
  res.json(items.sort((a, b) => a.quantity < b.quantity))
})

console.log("Starting server...")
app.listen(7879)

        

Where to get help

Got stuck? Don't worry! Join the discussion on Github (issue #7). It might be that the exercise could be clearer or there's something you really can't wrap your head around. That's totally fine! 🙂

You can also have a look at my solution. No shame in having a peek. 🧐
But do share your thoughts on the exercises, it would be really helpful!