Introduction

Welcome to our lesson on mastering data aggregation and data streams with JSON formatting in TypeScript. In this lesson, we'll start by building a basic sales records aggregator. Leveraging TypeScript's type safety, the lesson will empower you with strong typing benefits, ensuring your data handling is robust and error-free. By the end of this session, you'll be able to manage and format data streams efficiently using TypeScript.

Starter Task Methods and Their Definitions

To begin, we'll implement a basic sales record aggregator. Here are the methods we'll be focusing on:

  • addSale(saleId: string, amount: number): void - Adds a sale record with a unique identifier saleId and an amount. If a sale with the same saleId already exists, it updates the amount.

  • getSale(saleId: string): number | undefined - Retrieves the sale amount associated with the saleId. If the sale does not exist, it returns undefined.

  • deleteSale(saleId: string): boolean - Deletes the sale record with the given saleId. Returns true if the sale was deleted and false if the sale does not exist.

Are these methods clear so far? Great! Let's now look at how we would implement them in TypeScript.

Starter Task Solution

Here is the complete code for the starter task:

Explanation:

  • The constructor method initializes a private object sales to store records.
  • The addSale method adds a new sale or updates the amount for an existing sale ID.
  • The getSale method retrieves the amount for a given sale ID or returns undefined if it does not exist.
  • The deleteSale method removes the sale record for the given sale ID or returns false if the sale does not exist.

With the basic aggregator implemented, let's extend it with more advanced functionalities.

New Methods and Their Definitions

To increase the complexity and usefulness of our sales aggregator, we'll adjust some existing methods and introduce some new methods and functionalities involving JSON.

Let's define custom types to simplify the method return types and the sales attribute:

Here's the updated class with type definitions:

  • addSale(saleId: string, amount: number, date: string): void - Adds or updates a sale record with saleId, amount, and a date in the format "YYYY-MM-DD".

  • aggregateSales(minAmount: number = 0): AggregateResult - Returns an AggregateResult object with the total number of sales and the total amount of sales above minAmount.

  • formatSales(minAmount: number = 0): string - Returns sales data filtered by minAmount in JSON format, including aggregate statistics.

  • getSalesInDateRange(startDate: string, endDate: string): Sale[] - Retrieves sales within the specified date range.

Let's implement these methods step-by-step.

Step 1: Enhancing the 'addSale' Method to Include Date

We'll first modify the addSale method to accept a date.

This ensures each sale record includes a date in addition to the amount, maintaining type consistency.

Step 2: Implementing the 'aggregateSales' Method

Now, let's create the aggregateSales method:

This method iterates through the sales and sums those that exceed the minAmount, leveraging TypeScript's type annotations for safe computations.

Step 3: Implementing the 'formatSales' Method

The formatSales method is designed to output sales data as JSON, filtered by a specified minimum amount (minAmount) and including aggregated sales statistics. Below is an explanation of the key components of this method:

Method Chaining:

  1. Object.entries(this.sales):

    • This converts the sales object into an array of key-value pairs. Each pair is an array where the first element is the saleId and the second is a SaleRecord object containing the amount and date.
  2. filter(([_, sale]) => sale.amount > minAmount):

    • This filters the entries based on the condition that the sale's amount must be greater than the minAmount. The use of _ as a placeholder for implies it's not utilized in this operation.
Step 4: Implementing the 'getSalesInDateRange' Method

The getSalesInDateRange method is developed to retrieve sales records that fall within a specified date range.

Method Chaining:

  1. Object.entries(this.sales):

    • Converts the sales object into an array of key-value pairs. Each entry is an array [saleId, SaleRecord]. This allows the function to easily operate on each sale record.
  2. filter(([_, sale]) => { ... }):

    • Filters entries to include only those whose saleDate falls within the specified start and end dates.
    • The lambda function:
      • Converts the sale.date string into a Date object ().
Lesson Summary

Congratulations! You've now extended a basic sales aggregator to an advanced one capable of filtering, aggregating, and formatting data in JSON. TypeScript's strong typing offers significant advantages, such as type safety and prevention of runtime errors, especially when dealing with large datasets. Feel free to experiment further with TypeScript features to reinforce your understanding. Now, let's move on to the practice section to apply what you've learned!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal