Module 16 : Javascript Maps and Sets
π§ Concept Overview
πΉ What is a Map?
A Map is a collection of key-value pairs where:
Keys can be of any type (not just strings or symbols like in objects).
Maintains the insertion order of keys.
js
code
const myMap = new Map(); myMap.set('name', 'Alice'); myMap.set(100, 'number key'); myMap.set(true, 'boolean key');
πΉ What is a Set?
A Set is a collection of unique values.
Automatically removes duplicates.
Maintains the insertion order of values.
js
code
const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(2); // Duplicate - will not be added
π Difference Between Object, Array, Map, and Set
Feature
Object
Array
Map
Set
Key type
Strings/Symbols
Indexes
Any type
N/A (only values)
Order
Not guaranteed
Indexed order
Insertion order
Insertion order
Iteration
for...in
for, forEach
forEach, iterator
forEach, iterator
Duplicate keys
Not allowed
Allowed
Not allowed
Not allowed
π ️ Practical Methods
π§ Map Methods
Method
Description
Example
set(key, value)
Adds or updates a key-value pair
map.set('a', 1);
get(key)
Retrieves value for a key
map.get('a'); // 1
has(key)
Checks if key exists
map.has('a'); // true
delete(key)
Removes a key-value pair
map.delete('a');
clear()
Removes all entries
map.clear();
size
Returns the number of pairs
map.size;
π Map Iteration
js
code
const userMap = new Map([ ['name', 'John'], ['age', 30] ]); for (let [key, value] of userMap) { console.log(`${key}: ${value}`); }
π§ Set Methods
Method
Description
Example
add(value)
Adds a unique value
set.add(1);
has(value)
Checks if a value exists
set.has(1);
delete(value)
Removes a value
set.delete(1);
clear()
Removes all values
set.clear();
size
Returns the number of elements
set.size;
π Set Iteration
js
code
const fruits = new Set(['apple', 'banana', 'apple']); for (let fruit of fruits) { console.log(fruit); }
π§ͺ Practical Examples
π Example 1: Frequency Counter using Map
js
code
function countWords(str) { const words = str.split(' '); const wordMap = new Map(); for (let word of words) { word = word.toLowerCase(); wordMap.set(word, (wordMap.get(word) || 0) + 1); } return wordMap; } console.log(countWords('apple banana apple orange'));
π Example 2: Removing Duplicates using Set
js
code
function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
π Example 3: Caching with Map
js
code
const cache = new Map(); function expensiveCalculation(x) { if (cache.has(x)) return cache.get(x); let result = x * x; // Simulate expensive operation cache.set(x, result); return result; } console.log(expensiveCalculation(4)); // Calculates console.log(expensiveCalculation(4)); // Returns cached
π‘Research Understanding
1. Performance
Map performs better than objects for frequent additions/removals.
Set is more efficient for checking existence of values than arrays using .includes().
2. Memory Usage
Map and Set have optimized internal representations, especially for large collections.
3. Use Cases
Use Case
Preferred Data Structure
Caching
Map
Lookup Table
Map
Unique list of tags
Set
Duplicate removal
Set
Grouping data
Map
π Guidance
Introduce Maps and Sets conceptually.
Compare with Arrays and Objects.
π§ͺ Hands-On Demonstration
( examples (e.g., counting, duplicate removal).
Live code
π§ Practice Exercises Exercise 1: Create a map of countries and their capitals.
js
code
const countryMap = new Map(); // Add at least 5 countries with their capitals.
Exercise 2: Remove duplicates from a list of names using Set.
Exercise 3: Write a function that tracks how many times each character appears in a string using Map.
π§© Assignments
Build a Voting App
Use a Map to track votes for candidates and display a leaderboard.
Set Intersection Function
Write a function that returns the common elements between two arrays using Set.
π Summary
Feature
Map
Set
Stores key-value
✅
❌
Unique values
❌
✅
Maintains insertion order
✅
✅
Iterable
✅
✅
Keys/values of any type
✅
✅
π Conclusion
Understanding Map and Set is crucial for writing modern, efficient JavaScript code. They solve problems more elegantly than Object and Array in certain contexts. With proper usage, they lead to better performance, cleaner code, and fewer bugs.
No comments:
Post a Comment