ES6基本的语法(十二) Map模拟实现
2021-02-25 本文已影响0人
StevenTang
模拟实现 Map
首先上在一篇的文章我介绍了 Map 的主要特点
- 不重复
- 任何类型的值都可以作为属性
主要围绕这几点来写
还有 Map 里面的方法选择性实现几个 set(), get(), delete(), has(), clear()
。
const
function Op(){
this.bucketLength = 8; // 定义的桶的范围
this.init();
}
Op.prototype.init = function(){
// 初始化一个桶
this.bucket = new Array(this.bucketLength);
// for 循环 利用 type 标记是第几个桶 在生成 nxet
for(var i = 0; i < this.bucketLength;i++){
this.bucket[i] = {
type: 'bucket_' + i,
next: null
}
}
}
// hash
Op.prototype.makeHash = function(key){
// 要确定范围值 [0,8)
// 重复算值
if(typeof key !== 'string'){
if (typeof key == "number"){
// number 处理数字
has = object.is(NaN,NaN)? 0 : key
} else if (typeof key == "boolean"){
// boolean 处理布尔值
hash = +key; // 类型转换
} else if (typeof key == "object"){
// 处理 null {} []
hash = 7; // 如果是 object 固定写死 7
} else {
// 处理 undefined 和 function()
hash = 6;
}
} else {
// String 处理字符串
for(let i = 0; i < key.length;i++){
hash += key[i] ? key[i].charCodeAt(0) : 0;
}
return hash % this.bucketLength
}
}
Op.prototype.set = function(key,val){
let hash = this.makeHash(key) // 拿到 hash
let tempBucket = this.bucket[hash]; // 定位到桶的位置
while (tempBucket.next){
if(tempBucket.next.key == key){ // 判断 Key 是否相同
tempBucket.next.value = val;
return;
} else {
tempBucket = tempBucket.next;
}
}
tempBucket.next = {
key: key,
value : val,
next: null
}
}
Op.prototype.get = function(key){
let hash = this.makeHash(key);
let tempBucket = this.bucket[hash];
while (tempBucket){
if(tempBucket.key == key){ // 判断 Key 是否相同
return tempBucket.value;
} else {
tempBucket = tempBucket.next; // 因为初始化 会空转一圈
}
}
return undefined
}
Op.prototype.delete = function(key){
let hash = this.makeHash(key);
let tempBucket = this.bucket[hash];
while (tempBucket.next){
if(tempBucket.next.key == key){ // 判断 Key 是否相同
tempBucket.next = tempBucket.next.next
return;
} else {
tempBucket = tempBucket.next;
}
}
}
Op.prototype.has = function(){
let hash = this.makeHash(key);
let tempBucket = this.bucket[hash];
while (tempBucket.next){
if(tempBucket.next.key == key){ // 判断 Key 是否相同
return true;
} else {
tempBucket = tempBucket.next;
}
}
return false;
}
Op.prototype.clear = function(){
this.init();
}
let myP = new Op();
myP.set("name","ccc");
myP.set({},"xxx");
myP.get({});
myP.has({});
myP.delete({});
myP.clear();