// 原理: 链表、hash算法、桶
// 桶: 在桶内拟定8个空间, 链表: next, hash算法: 把不定的值变为特定范围的值 [0, 8)
// 用数组拟定为桶,桶内8个空间
// 传入的值可能为 object,array,string,number,undefined,NaN,boolean…
// 将传入的值通过hash算法求出[0, 8)的特定值,最后通过链表插入
// 1.不重复
// 2.字符串 数值 NaN null [] {} function(){}…
// 3.set get delete has clear
function Map () {
this.bucketLen = 8;
this.init();
}
Map.prototype.init = function () {
this.bucket = new Array(this.bucketLen);
for(var i = 0; i < this.bucketLen; i++){
this.bucket[i] = {
type: 'bucken_' + i,
next: null
}
}
}
Map.prototype.hash = function (key) {
var hash = 0;
if(typeof key != 'string'){
if(typeof key == 'number'){
hash = Object.is(key, NaN) ? 0 : key;
}else if(typeof key == 'object'){
hash = 1;
}else if(typeof key == 'boolean'){
hash = +key;
}else{
hash = 2;
}
}else{
for(var i = 0; i < 3; i++){
hash += key[i] ? key.charCodeAt(i) : 0;
}
}
return hash % 8;
}
Map.prototype.set = function (key, val) {
var hash = this.hash(key);
var oTempBucket = this.bucket[hash];
while(oTempBucket.next){
if(oTempBucket.next.key){
oTempBucket.next.key = val;
}else{
oTempBucket = oTempBucket.next;
}
}
oTempBucket.next = {
key: key,
val: val,
next: null
}
}
Map.prototype.get = function (key) {
var hash = this.hash(key);
var oTempBucket = this.bucket[hash];
while(oTempBucket.next){
if(oTempBucket.next.key == key){
return oTempBucket.next.val;
}else{
oTempBucket = oTempBucket.next;
}
}
return undefined;
}
ES6-Map
最新推荐文章于 2024-08-02 14:21:03 发布