Combine Small Functions Into a Report

You’ve built three pieces of a feedback report so far. selectByTopic() hands back the messages about one topic, .length turns that list into a count, and in the last exercise you returned a result object with topic, count, and matchingMessages instead of a sentence. Each piece works on its own. Now it’s time to make them work together.

In this lesson, you’ll use a short brief to plan the functions for a small report, specifying what each one takes and returns. Then you’ll connect them, check each one with a known example, and follow the investigation of a count that comes out wrong.

Plan the Functions From the Brief

Here’s the brief for the report:

For any topic, the app needs to know the topic, how many messages are about it, and which messages they are, so that a reader can open each one and check it. The app then shows the report on the screen.

Before you look at any code, take a moment to write your own plan. List the functions you’d write, and for each one, give it a verb name and say what it takes and returns. Then mark the one function that logs anything.

Done? Here’s one plan, written as comments, the way you might sketch it before writing a single line of code:

Language: JavaScript
// selectByTopic(messages, topic)
//   returns the messages about topic, whole, in order
// buildTopicReport(messages, topic)
//   returns a result object: topic, count and
//   matchingMessages
// showReport(report), supplied by the app
//   logs the report and returns nothing

Each comment names one job, and each job becomes one function. Only showReport() logs, and it sits at the very edge of the plan. The two functions you write hand their answers back with return and never touch the screen.

If your list had a single function that selects, counts, and logs, try asking yourself about each job: Could I check this step on its own? A function that does everything gives you nothing smaller to check or reuse.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.