Using Maps in TypeScript for Efficient Element Counting

Topic Overview

In this lesson, we will explore the concept and practical use of Maps in TypeScript. Maps are a powerful and efficient data structure for storing key-value pairs. We'll use a Map to count the frequency of elements in a collection, understand its mechanics, and analyze its time and space efficiency. Through step-by-step demonstrations and detailed code examples, we'll uncover the practical applications of Maps in various contexts.

Understanding the Problem

Imagine a paint store where we need to count the cans of paint in different colors. Manually counting each one becomes inefficient as the collection grows. A more efficient method employs a Map. Consider this list of colors:

const colors: string[] = ["red", "blue", "red", "green", "blue", "blue"];

Manually, red appears twice, blue three times, and green once. Using a Map can streamline this process.

Introducing Maps

Maps allow us to store and retrieve data using keys. In our example, the unique colors in our list are the keys and their counts are the values. Let's use TypeScript's Map to count elements in our colors list.

First, we'll initialize our Map to store the counts:

const colors: string[] = ["red", "blue", "red", "green", "blue", "blue"];
const colorMap: Map<string, number> = new Map();

Calculating the Value

Next, we need to calculate the value to set for each key. If the key is encountered for the first time, we set its value to 1; otherwise, we increment its value by one:

if (colorMap.get(color)) {
    colorMap.set(color, colorMap.get(color)! + 1);
} else {
    colorMap.set(color, 1);
}

In the line colorMap.set(color, colorMap.get(color)! + 1);, the ! operator is the non-null assertion operator in TypeScript. It is used here to inform TypeScript that we expect colorMap.get(color) to not be undefined at this point, allowing us to safely add 1 to the value.

However, this approach is inefficient because we retrieve the value in the map twice. A more efficient approach combines the if-statement using short-circuit evaluation, reducing the number of times colorMap.get(color) is called from twice to once:

colorMap.set(color, (colorMap.get(color) || 0) + 1);

Here, we check if the given color is already a key in the Map. If it is, we set its value to colorMap.get(color)! + 1, effectively incrementing it by 1. If not, the get() function returns undefined, and we set its value to 0 + 1, initializing it to 1. The ! operator is no longer necessary in this more efficient approach because the logical || operator ensures the value is always a number before incrementing.

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