Welcome! The focus of today's lesson is on data aggregation, a practical concept utilizing Maps as our primary tool. In TypeScript, we leverage its rich type system to ensure safer and more robust code.
Data aggregation refers to gathering "raw" data and subsequently presenting it in an analysis-friendly format. An illustrative analogy is viewing a cityscape from an airplane, providing an informative aerial overview rather than delving into the specifics of individual buildings. We will guide you through operations such as Sum, Average, Count, Maximum, and Minimum for practical, hands-on experience, using TypeScript's types for enhanced reliability and clarity.
Let's continue!
We will begin with a hands-on example using a fruit basket represented as a Map
. First, create a new Map
with type annotations and set the quantities of various fruits:
Next, sum the values in the Map
. Start with a variable to hold the total number of fruits, explicitly typing it:
Finally, print the total:
Counting the number of fruit types in our basket corresponds to counting the number of keys in our Map
. Start by creating the Map
again, with type annotations:
Then, count the elements using the size
property:
The spread operator (...
) allows an iterable such as an array, string, or Map
to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. It is useful for tasks such as copying or merging arrays, passing a variable number of arguments to functions, and working with Maps
.
For instance, consider our fruit basket Map
from earlier. You can use the spread operator to convert the Map
's values into an array:
Similarly, you can convert the keys into an array:
One directly applicable use case of the spread operator is finding the highest and lowest values in a Map
. TypeScript allows us to use Math.max
and Math.min
with proper type definitions:
Similarly, you can find the minimum value using Math.min
:
To calculate the average number of each type of fruit, first sum the values as demonstrated previously, with type annotations:
Then, calculate the average by dividing the total quantity of fruits by the number of fruit types, again using type annotations:
Congratulations on learning about data aggregation using TypeScript! You have mastered the Sum, Count, Max, Min, and Average operations. By ensuring that your code is type-safe, you've enhanced its reliability and readability. The skills you have acquired in data aggregation using Map
are invaluable across a vast array of data analysis tasks, such as report generation and decision-making processes. TypeScript not only improves the robustness of your code but also facilitates earlier error detection during development. Happy coding!
