Javascript之数据结构与算法的Dictionary实现
1.自实现Dictionary
class Dictionary{
constructor(){
this.items={}
}
has(key){
return key in this.items;
}
set(key,value){
this.items[key]=value;
}
delete(key){
if(this.has(key)){
delete this.items[key];
return true;
}
return false;
}
get(key){
return this.has(key) ? this.items[key]:undefined;
}
values(){
var values=[];
for(let k in this.items){
if(this.has(k)){
values.push(this.items[k]);
}
}
return values;
}
keys(){
return Object.keys(this.items);
}
getItems(){
return this.items;
}
clear(){
this.items={};
}
size(){
return Object.keys(this.items).length;
}
}
let dictionary=new Dictionary();
dictionary.set('john','johnsname@email.com');
console.log(dictionary.has('john'));
console.log(dictionary.size());
console.log(dictionary.keys())
console.log(dictionary.values())
console.log(dictionary.get('john'))
console.log(dictionary.getItems())
2.Es6中Map对比
let map=new Map();
map.set('Gandalf', 'gandalf@email.com');
map.set('John', 'johnsnow@email.com');
map.set('Tyrion', 'tyrion@email.com');
console.log(map.has('Gandalf')); //输出true
console.log(map.size); //输出3
console.log(map.keys()); //输出["Gandalf", "John", "Tyrion"]
console.log(map.values()); //输出["gandalf@email.com","johnsnow@email.com", "tyrion@email.com"]
console.log(map.get('Tyrion')); //输出tyrion@email.com
console.log(map.delete("John"));
3.Map总结
和我们的Dictionary类不同, ES6的Map类的values方法和keys方法都返回Iterator,而不是值或键构成的数组。另一个区别是,我们实现的size方法返回字典中存储的值的个数,而ES6的Map类则有一个size属性。
删除map中的元素可以用delete方法:
map.delete(‘John’);
clear方法会重置map数据结构,这跟我们在Dictionary类里实现的一样。
4.Es6中WeakMap类和WeakSet类
//Es6中WeakMap类和WeakSet类
let map=new WeakMap();
var ob1 = {name:'Gandalf'}, //
ob2 = {name:'John'},
ob3 = {name:'Tyrion'};
map.set(ob1, 'gandalf@email.com'); //
map.set(ob2, 'johnsnow@email.com');
map.set(ob3, 'tyrion@email.com');
console.log(map.has(ob1)); // 输出true
console.log(map.get(ob3)); // 输出tyrion@email.com
map.delete(ob2); //
总结:
除了Set和Map这两种新的数据结构, ES6还增加了它们的弱化版本, WeakSet和WeakMap。
基本上, Map和Set与其弱化版本之间仅有的区别是:
- WeakSet或WeakMap类没有entries、 keys和values等方法;
- 只能用对象作为键。
- WeakMap类也可以用set方法,但不能使用数字、字符串、布尔值等基本数据类型,需要将名字转换为对象。
- 同样的逻辑也适用于WeakSet类
优点:
1.创建和使用这两个类主要是为了性能。 WeakSet和WeakMap是弱化的(用对象作为键),没有强引用的键。这使得JavaScript的垃圾回收器可以从中清除整个入口。
2.必须用键才可以取出值。这些类没有entries、 keys和values等迭代器方法,因此,除非你知道键,否则没有办法取出值。即可使用WeakMap类封装ES6类的私有属性。