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 identifiersaleIdand anamount. If a sale with the samesaleIdalready 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. Returnstrueif the sale was deleted andfalseif 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
constructormethod initializes a private objectsalesto store records. - The
addSalemethod adds a new sale or updates the amount for an existing sale ID. - The
getSalemethod retrieves the amount for a given sale ID or returnsundefinedif it does not exist. - The
deleteSalemethod removes the sale record for the given sale ID or returnsfalseif 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 adatein the format "YYYY-MM-DD". -
aggregateSales(minAmount: number = 0): AggregateResult- Returns anAggregateResultobject with the total number of sales and the total amount of sales aboveminAmount. -
formatSales(minAmount: number = 0): string- Returns sales data filtered byminAmountin 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
salesobject into an array of key-value pairs. Each pair is an array where the first element is thesaleIdand the second is aSaleRecordobject 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
salesobject 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
saleDatefalls within the specified start and end dates. - The lambda function:
- Converts the
sale.datestring into aDateobject ().
- 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!
