This is the 20th day of my participation in the More text Challenge. For more details, see more text Challenge
What is a dictionary
A dictionary is a data structure used to store unique values, usually in the form of pairs of keys and values, also known as mappings. The collections we mentioned in the last article store elements in the form of values. The es6 implementation of the Map class is what we call a dictionary.
Create a dictionary
- Set (key, value): Adds a new element to the dictionary.
- Remove (key): Use the key to remove the corresponding data value from the dictionary.
- Has (key): True if a key value exists in the dictionary, false otherwise.
- Get (key): Finds a specific value by a key and returns it.
- Clear (): Removes all elements from the dictionary.
- Size (): Returns the number of elements contained in the dictionary. Similar to the length property of an array.
- Keys (): returns all the key names in the dictionary as an array.
- Values (): returns all the values in the dictionary as an array.
function Dictionary () {
let items = {}
this.has = function (key) {
return key in items
}
this.set = function (key, value) {
items[key] = value
}
this.remove = function (key) {
if(this.has(key)){
delete items[key]
return true
}
return false
}
this.get = function (key) {
if(this.has(key)) {
return items[key]
}
return undefined
}
this.values = function () {
let values = []
for(let key in items) {
// Check if the attribute is private and return only the private attribute, avoiding returning all attributes on the prototype chain
if(this.hasOwnProperty(key)){
values.push(items[key])
}
}
return values
}
this.keys = function () {
return Object.keys(items)
}
this.clear = function () {
items = {}
}
this.size = function () {
return Object.keys(items).length
}
}
Copy the code
Now that we’ve implemented a simple, basic dictionary class, let’s create an instance to verify:
let dictionary = new Dictionary()
dictionary.set('A'.'aaa')
dictionary.set('B'.'bbb')
dictionary.set('C'.'ccc')
console.log(dictionary.has('A')) // true
console.log(dictionary.size()) / / 3
console.log(dictionary.get('B')) // 'bbb'
console.log(dictionary.keys()) // ['A', 'B', 'C']
console.log(dictionary.values()) // ['aaa', 'bbb', 'ccc']
Copy the code
In the above code, we can clearly see the output, which validates our dictionary class.
Dictionary, compared with our English-Chinese dictionary, english-Chinese dictionary itself can be regarded as a collection of key and value pairs. For example, if we want to find out what is the meaning of “beautiful”, we can naturally open the dictionary and find that “beautiful” is “beautiful”. In this case, “beautiful” is the key name and “beautiful” is the key value.