Exercise: Food Truck Orders
Finish the Rolling Noodle food truck's order functions, a day's total with reduce, one dish's orders with filter, receipt lines with map and destructuring, JSON both ways and an async loader with a clear error, and let node --test check each one.
Apprentice · Node.js · JavaScript · Updated
The Rolling Noodle, a food truck, saves each day's orders as a JSON file, and at closing time its owner adds them up by hand on the back of a napkin. You'll finish the functions that do it for her: the day's total, the orders for one dish, a receipt line for every order, the orders as JSON and back, and a loader that waits for the file's text and says clearly when the file is broken. It's the JavaScript Node code leans on, put to work on one real job, and tests check every function as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-food-truck-orders, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:
cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-food-truck-orders.git
Git makes a folder, exercise-node-food-truck-orders, with the exercise code inside. Open that folder in VS Code (File > Open Folder) and open its terminal with Terminal > New Terminal. This exercise uses no packages, only what comes with Node, so there's nothing to install. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.
The folder holds:
orders.js: the six functions, for you to finish.orders.json: the day's six orders. Each has anid, acustomer, adish, aquantityand aprice, the price of one dish in dollars.main.js: readsorders.jsonwith yourloadOrdersand prints the day: a receipt line for every order, how many orders were for Spicy Peanut Noodles, and the total.orders.test.js: the tests, which call each of your functions and check what comes back. You don't need to change it.
What to do
orders.js already exports the six functions. For now each one throws an error that says it isn't built yet. The comment at its top says what each should return, using the six orders in orders.json:
dayTotal(orders) 97.75: each order's quantity times its price, all added up
dayTotal([]) 0: no orders, nothing earned
ordersFor(orders, "Spicy Peanut Noodles") an array of orders 1 and 4, Maya's and Sam's, in that order
ordersFor(orders, "Tofu Bowl") [], an empty array: no order is for that dish
receiptLines(orders) an array with one line of text for each order, in the same order:
"#1 Maya: 2 x Spicy Peanut Noodles = $19.00"
the order's id, customer, quantity, dish, and its cost (quantity
times price) with two decimal places
toJson(orders) the orders as JSON text with no spaces or line breaks. For an array
holding order 2 alone, it returns
'[{"id":2,"customer":"Jordan","dish":"Garlic Ramen","quantity":1,"price":11}]'
fromJson(text) the orders back as data, from JSON text like that: for the text
above, an array holding order 2
loadOrders(readText) an async function. readText is a function that gives back a promise
of the orders file's text. loadOrders awaits it and returns the
orders as data: the six orders for orders.json's text, and [] for
the text "[]". When the text isn't valid JSON, such as
"Maya: 2 noodles", it throws an Error with the message
"The orders file isn't valid JSON."
Work through order 1 by hand first: Maya ordered 2 Spicy Peanut Noodles at $9.50 each, so her order costs 2 times 9.5, which is 19, and her receipt line is #1 Maya: 2 x Spicy Peanut Noodles = $19.00. Add up all six orders' costs the same way, 19 + 11 + 18.75 + 9.5 + 17.5 + 22, and you get the day's 97.75.
- Finish
dayTotal, which adds up every order's cost, and starts from 0 so an empty day is 0. - Finish
ordersFor, which keeps only the orders for one dish. - Finish
receiptLines, which turns each order into its line of text. - Finish
toJsonandfromJson, which turn the orders into JSON text and back. - Finish
loadOrders: await the text fromreadText(), turn it into data, and when that fails, throw anErrorwith the messageThe orders file isn't valid JSON.
Keep each function's name and its export. Write each as a function declaration or an arrow function, whichever you like.
Check your work
Run the tests from the exercise folder:
npm test
At first all 11 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it expected and what came back, for example dayTotal(orders) should return 97.75, but it returned 0. The tests hand loadOrders a pretend reader, a small async function that gives back text, so they never read a file.
To see the whole day, run npm start. Until every function works, it stops with an error such as Not built yet: loadOrders.
Hints
- A total is a job for reduce. reduce adds up a list with a starting value. Each step adds one order's quantity times its price to the running total.
- Keep, or turn into? map and filter shows both: filter keeps some of the items as they are, and map turns every item into something new, such as a line of text.
- Unpack each order where it arrives. Destructuring works in a parameter too:
({ id, customer }) => ...hands you the order's parts by name. - Two decimal places, every time.
(19).toFixed(2)gives the text"19.00", and(18.75).toFixed(2)gives"18.75". - JSON both ways. JSON: Data You Can Save and Send shows
JSON.stringifyandJSON.parse, and the errorJSON.parsethrows on text that breaks JSON's rules. - Wait first, then parse. async and await shows how to wait for a promise inside an async function, and Handling Errors with try, catch and finally shows how to catch an error and throw a clearer one in its place.
When you're done
Every test is green, and npm start prints the Rolling Noodle's day:
> start
> node main.js
The Rolling Noodle: today's orders
#1 Maya: 2 x Spicy Peanut Noodles = $19.00
#2 Jordan: 1 x Garlic Ramen = $11.00
#3 Priya: 3 x Pork Dumplings = $18.75
#4 Sam: 1 x Spicy Peanut Noodles = $9.50
#5 Lena: 2 x Veggie Lo Mein = $17.50
#6 Omar: 2 x Garlic Ramen = $22.00
Spicy Peanut Noodles orders: 2
Day total: $97.75
Now look back at loadOrders. It never reads a file itself: it awaits whatever function it's handed. How does that let the tests check it without any file, and what would main.js pass it to read tomorrow's orders from another file?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-node-food-truck-orders), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-node-food-truck-orders.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-node-food-truck-orders, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
A day of orders as an array of objects, totals with reduce, JSON in and out, and an async step that can fail: that's the shape of nearly every Node program you'll write, from a command-line tool to an API, and now you've built each piece once.