What is a Map Data Structure?
A Map is a data structure that stores key-value pairs, where each key is unique and maps to a specific value. In JavaScript (and MongoDB/Mongoose), a Map allows you to efficiently look up, insert, and remove elements based on keys.
Think of a Map like a dictionary, where you can quickly find a value if you know the key.
Key Characteristics of a Map:
Key-Value Pair: Each element in a Map is a pair where a unique key maps to a specific value.Fast Access: You can quickly retrieve the value associated with a key.Unique Keys: Each key in a Map must be unique, meaning you cannot have two entries with the same key.Flexible Value Types: The values can be any type (string, number, object, etc.), and in this case, we're using numbers (for unread message counts).
Example of a Map:
const unreadMessages = new Map();
unreadMessages.set('user123', 5); // user123 has 5 unread messages
unreadMessages.set('user456', 3); // user456 has 3 unread messages
set(key, value): Adds a key-value pair to the Map or updates an existing one.get(key): Retrieves the value associated with the key. For example: unreadMessages.get('user123') would return 5.has(key): Checks if the Map contains a key. For example: unreadMessages.has('user123') would return true.delete(key): Removes the key-value pair for a key.
Real-life Example:
const unreadMessages = new Map();
unreadMessages.set("user123", 5); // User with ID 'user123' has 5 unread messages
if (unreadMessages.has("user123")) {
unreadMessages.set("user123", unreadMessages.get("user123") + 1); // Increment the count
} else {
unreadMessages.set("user123", 1); // First unread message for this user
}