Applying Maps for Real-World Challenges in TypeScript

Introduction and Goal Setting

Hello there! In this lesson, we will apply Maps to real-world challenges. Our focus will be on solving tasks such as cataloging books in a library, counting votes in an election, and tracking inventories.

Real-World Application: Cataloging Books in a Library

Suppose you're asked to manage the cataloging of books in a library. Here, the book ID serves as the key, while the details of the book, such as the title, author, and year of publication, are stored as values. This approach allows us to add, search for, and remove books from our library catalog using TypeScript, with enhanced readability and error-checking through type annotations.

TypeScript
// Type definitions for book details
type BookDetails = Map<string, string>;

// Initializing a Map with type annotations
let libraryCatalog: Map<string, BookDetails> = new Map();

// Details of a book
let bookId: string = "123";
let bookDetails: BookDetails = new Map([
    ["title", "To Kill a Mockingbird"],
    ["author", "Harper Lee"],
    ["year_published", "1960"]
]);

libraryCatalog.set(bookId, bookDetails);  // Adding a book to library catalog, where the value itself is a Map

// Searching for a book
if (libraryCatalog.has(bookId)) {
    let details: BookDetails | undefined = libraryCatalog.get(bookId);
    if (details) {
        console.log(`Title: ${details.get("title")}, Author: ${details.get("author")}, Year Published: ${details.get("year_published")}`);
    }
}

libraryCatalog.delete(bookId);  // Removing a book from the library

With the use of TypeScript, our Maps make the task of cataloging books in the library more efficient, readable, and type-safe.

Real-World Application: Counting Votes in an Election

Imagine a scenario in which we need to count votes in an election. By employing a Map, where each name is a unique key, and the frequency of that name serves as the associated value, we can efficiently count votes. Below is the TypeScript code to achieve this:

TypeScript
let votesList: string[] = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Alice"];  // Cast votes
let voteCounts: Map<string, number> = new Map();  // Initializing a Map

// Counting the votes
for (let name of votesList) {
    voteCounts.set(name, (voteCounts.get(name) || 0) + 1);
}

for (let [candidate, count] of voteCounts) {
    console.log(`${candidate}: ${count}`);
}
// Prints: Alice: 3, Bob: 2, Charlie: 1

This TypeScript implementation of Maps offers a succinct and robust method for counting votes, providing both clarity and safety through type annotations.

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