Write Reusable Reporting Functions (Summary)

At the start of this course, you had a working block that counted delivery messages, and a second report meant copying it. Now you write the counting rule once, give it a name, and run it for any topic on any set of messages. Well done making it this far!

Here’s what you can now do, with the names you used along the way:

  • Turn a copied block into a function with parameters, then call it with different arguments, as logTopicCount(messages, "billing") reused the rule for another topic.
  • Hand a result back with return so the calling code can store it, add it up, or pass it on. A function that only logs gives back undefined, which is how your first total came out as NaN.
  • Declare variables where they’re needed by putting let count = 0; inside the function. Every call starts fresh, so the billing report never starts from the delivery count.
  • Build a fresh result object with topic, count, and matchingMessages, so every number arrives with the records behind it.
  • Plan a report as small functions from a brief, each with a verb name, its inputs, and its result, and with the logging left to the supplied showReport() at the edge.
  • Investigate a wrong count by shrinking the data until you can count by hand, then testing one idea about the cause. You traced a count of 1 instead of 3 to a return inside the loop in selectByTopic(), which handed back the list after the first match.

Here are the two functions from your project, run on this week’s messages:

Language: JavaScript
const messages = [
  { id: "M-301", topic: "delivery", text: "Box came late" },
  { id: "M-302", topic: "billing", text: "Charged twice" },
  { id: "M-303", topic: "delivery", text: "Wrong address" },
  { id: "M-304", topic: "app", text: "Login fails" },
  { id: "M-305", topic: "billing", text: "No refund yet" },
  { id: "M-306", topic: "delivery", text: "Left in rain" },
];

function selectByTopic(messages, topic) {
  const selected = [];
  for (const message of messages) {
    if (message.topic === topic) {
      selected.push(message);
    }
  }
  return selected;
}

function buildTopicReport(messages, topic) {
  const matchingMessages = selectByTopic(messages, topic);
  return {
    topic: topic,
    count: matchingMessages.length,
    total: messages.length,
    matchingMessages: matchingMessages,
  };
}

const report = buildTopicReport(messages, "delivery");
console.log(report.topic, report.count, "of", report.total);
for (const message of report.matchingMessages) {
  console.log(message.id);
}

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.