Sobes.tech
Junior

Why did you use map and set data structures in your work?

sobes.tech AI

Answer from AI

Map is used for storing key-value pairs, where keys are unique. It is convenient for quick lookup of values by key, for example, for caching data or linking DOM elements with their logical representations.

Set is used for storing a collection of unique values. It is useful for removing duplicates from an array, checking for the presence of an element in a collection, or counting unique elements.

Examples of usage:

  • Tracking active users by their ID in a Map for quick access to their data.
  • Creating a collection of unique tags from a list of articles using Set.
  • Caching the results of function calls: key — arguments, value — result.
  • Removing duplicate elements from a list of identifiers.
// Example of using Map
const userCache = new Map();

function getUserData(userId) {
  if (userCache.has(userId)) {
    console.log("Data from cache");
    return userCache.get(userId);
  }

  // Simulating an API request
  const userData = { id: userId, name: `User ${userId}` };
  userCache.set(userId, userData);
  console.log("Data from API, added to cache");
  return userData;
}

getUserData(1);
getUserData(1);
getUserData(2);

// Example of using Set
const tags = ['javascript', 'css', 'html', 'javascript', 'react', 'css'];
const uniqueTags = new Set(tags);

console.log([...uniqueTags]); // ['javascript', 'css', 'html', 'react']
console.log(uniqueTags.has('angular')); // false

Comparison table of Map and Set:

Feature Map Set
Purpose Storing key-value pairs Storing unique values
Keys Unique, any types Not used
Values Any types Unique, any types
Search By key Checking for value presence
Duplicates No (for keys) No (for values)