JavaScript: How to implement a dictionary/map in 3mins.
chinedu | ddevguys
Posted on January 18, 2021
We do know that JavaScript isn’t a statically typed language.
So how in the world can we implement dictionaries with it.
Well, stick with me champ! Because you are about to find out.
Up until ES6 when maps were created. JavaScript had no native support for dictionaries.
But there was a flexible way of implementing a dictionary using the JavaScript object.
This may sound funny to people coming from other statically typed languages, but this is true and its because JavaScript gives us flexible ways to use objects because it’s a dynamically typed language.
Introduction
What is a Dictionary?
A dictionary can also be called a map in JavaScript, and maps/dictionaries are used to store unique elements of key-value pairs.
They are similar to the set
data structure only that the set data structure stores a unique element of value value
pairs.
Thanks to es6(ECMAScript 6) JavaScript now has an implementation of a map which could also be interchangeably called dictionaries.
Let’s implement a map/dictionary shall we?
If you are a constant reader of mine, you’d know that we as always implement the skeletal structure of our class so as to keep us on track and guide.
class dictionaryOrMap {
constructor(){
this.element = {}
}
//methods go here
has(key)
set(key, value)
remove(key)
get(key)
clear()
size()
keys()
values()
}
Taking a look at our class constructor property, we see that we are going to be storing our element in a JavaScript object.
This is unlike the stacks
and queues
where we used an array
.
Let’s start implementing each methods of our dictionary class.
has
The has
method returns
true
if the key exists and false
if the key does not.
The has
method is a utility method that will play a vital role in helping us implement the methods of our dictionary/map class.
To implement this function, we use the for…in
loop to iterate all the properties of our objects.
To understand and dive deeper into how the for..in
loop works checkout the Mozilla Doc.
has(key){
return key in this.element
}
So, what the has
method does for us is to verify if we truly have the key as a property in our object.
set
This method adds a new element to the dictionary.
The set method receives a key-value
parameter.
Then we use our passed in value
and set it to the key
of our element object.
set(key, value){
return this.element[key] = value
}
As simple as that.
delete
This method uses the key
to remove a value from the dictionary.
To implement this method, we first have to search for the key
.
Then we use JavaScript’s delete
property or method to remove the key
attribute from our element object.
In a case where we delete, we want to return true
but, in a case, where we don’t, we want to return false
.
delete(key){
if(this.has(key)){
delete this.element[key]
return true
}
return false
}
*get *
The get
method helps us to return
a specific value by the key
we passed into our method.
get(key){
if(this.has(key)){
return this.element[key]
} else {
return undefined
}
values
The values
method returns all our values
in the element
object of our dictionary in an array.
There are two ways of implement this method we would see the both of them in this section.
The first method
First off, we want to loop through all the elements
in our object, this tells us that we actually have values
in our dictionary.
Then we would employ the has
method once again to verify the keys
.
If they do not exist then we push
them into the array
and return
all the values
.
Note: we verify the keys because the object prototype contains additional properties of its own.
values(){
let values = []
for(let k in this.element){
if(this.has(k)){
values.push(this.element[k])
}
}
return values
}
The second method
For the second method we use Object.values
to get all the values of our dictionary.
values(){
return Object.values(this.element)
}
Which method do you prefer? Let me know in the comments 😉😉😉😉.
key
This method returns
the array
of all the keys
in our dictionary.
In other to achieve this we use the Object.keys
, and passing in our object’s element as a parameter.
Key(){
return Object.keys(this.element)
}
size
This gives us the number of elements that are contained in our dictionary, this is similar to the length
property of an array.
size(){
return Object.keys(this.element).length
}
clear
This method removes all the elements from the dictionary just like its name sounds.
clear(){
return this.element = {}
}
With this, we have completely implemented or dictionary.
Dictionary or maps should be used whenever we are trying to solve a problem that has to be unique(element) and needs to be in a key-value pair format.
Let’s Test out our Dictionary
First, we instantiate our class
let map = new dictionaryOrMaps()
Let’s test the set
method
map.set("Vivian", "African")
map.set("Shalom", "Hispanics")
map.set("Gideon", "Caucasian")
Let’s test the has
method
//The result should be true
console.log(map.has("Vivian"))
Let’s test our size
method
//The result should be 3
console.log(map.size())
Let’s test our keys
method
//Result => ["Vivian", "Shalom", "Gideon"]
console.log(map.keys())
Let’s test our values
method
//Result => ["African", "Hispanics", "Caucasian"]
console.log(map values())
Let’s test the get
method
//Result => ["African"]
console.log(map.get("Vivian"))
Let’s test the remove
method
console.log(map.remove("Vivian"))
Finally, let's test to see if the key
and its value
were removed and if the size
was reduced too.
//Results
//["shalom", "Gideon"]
//["Hispanics", "Caucasian"]
//2
console.log(map.keys())
console.log(map.values())
console.log(map.size())
Hey you, yes you champ! Thanks for hanging in with me till the very last moment.
If you enjoyed pls follow me on Twitter and Instagram, if there are any improvements or code errors do let me know in the comment section below or a dm.
Thanks once again and bye for now. Much Love❤❤❤.
Posted on January 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.