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.
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 identifiersaleId
and anamount
. If a sale with the samesaleId
already exists, it updates the amount. -
getSale(saleId: string): number | undefined
- Retrieves the sale amount associated with thesaleId
. If the sale does not exist, it returnsundefined
. -
deleteSale(saleId: string): boolean
- Deletes the sale record with the givensaleId
. Returnstrue
if the sale was deleted andfalse
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.
Here is the complete code for the starter task:
Explanation:
- The
constructor
method initializes a private objectsales
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 returnsundefined
if it does not exist. - The
deleteSale
method removes the sale record for the given sale ID or returnsfalse
if the sale does not exist.
With the basic aggregator implemented, let's extend it with more advanced functionalities.
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 withsaleId
,amount
, and adate
in the format "YYYY-MM-DD". -
aggregateSales(minAmount: number = 0): AggregateResult
- Returns anAggregateResult
object with the total number of sales and the total amount of sales aboveminAmount
. -
formatSales(minAmount: number = 0): string
- Returns sales data filtered byminAmount
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.
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.
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.
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:
-
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 thesaleId
and the second is aSaleRecord
object containing the amount and date.
- This converts the
-
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.
- This filters the entries based on the condition that the sale's amount must be greater than the
The getSalesInDateRange
method is developed to retrieve sales records that fall within a specified date range.
Method Chaining:
-
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.
- Converts the
-
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 aDate
object ().
- Converts the
- Filters entries to include only those whose
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!
