Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The Dictionary Class in Javascript
JavaScript doesn't have a built-in Dictionary class, but we can create our own using objects or the Map class. Here's a complete implementation of a custom Dictionary class called MyMap.
Complete Dictionary Implementation
class MyMap {
constructor() {
this.container = {};
}
display() {
console.log(this.container);
}
hasKey(key) {
return key in this.container;
}
put(key, value) {
this.container[key] = value;
}
delete(key) {
if (this.hasKey(key)) {
delete this.container[key];
return true;
}
return false;
}
get(key) {
return this.hasKey(key) ? this.container[key] : undefined;
}
keys() {
return Object.keys(this.container);
}
values() {
let values = [];
for (let key in this.container) {
values.push(this.container[key]);
}
return values;
}
clear() {
this.container = {};
}
forEach(callback) {
for (let prop in this.container) {
callback(prop, this.container[prop]);
}
}
}
Using the Dictionary
// Create a new dictionary
let myDict = new MyMap();
// Add key-value pairs
myDict.put("name", "John");
myDict.put("age", 30);
myDict.put("city", "New York");
// Display the dictionary
myDict.display();
// Get values
console.log("Name:", myDict.get("name"));
console.log("Age:", myDict.get("age"));
// Check if key exists
console.log("Has 'email':", myDict.hasKey("email"));
console.log("Has 'name':", myDict.hasKey("name"));
{ name: 'John', age: 30, city: 'New York' }
Name: John
Age: 30
Has 'email': false
Has 'name': true
Dictionary Operations
let dict = new MyMap();
dict.put("apple", 5);
dict.put("banana", 3);
dict.put("orange", 8);
// Get all keys and values
console.log("Keys:", dict.keys());
console.log("Values:", dict.values());
// Use forEach to iterate
console.log("Iterating through dictionary:");
dict.forEach((key, value) => {
console.log(`${key}: ${value}`);
});
// Delete a key
console.log("Deleted 'banana':", dict.delete("banana"));
dict.display();
Keys: [ 'apple', 'banana', 'orange' ]
Values: [ 5, 3, 8 ]
Iterating through dictionary:
apple: 5
banana: 3
orange: 8
Deleted 'banana': true
{ apple: 5, orange: 8 }
Key Features
| Method | Purpose | Returns |
|---|---|---|
put(key, value) |
Add or update key-value pair | void |
get(key) |
Retrieve value by key | value or undefined |
hasKey(key) |
Check if key exists | boolean |
delete(key) |
Remove key-value pair | boolean |
keys() |
Get all keys | array |
values() |
Get all values | array |
Conclusion
This custom MyMap class provides dictionary functionality in JavaScript with methods for adding, retrieving, and managing key-value pairs. It's a useful alternative when you need dictionary-like behavior with custom methods.
Advertisements
