Map底层实现
function MyHashMap() {
this.init();
}
MyHashMap.prototype.init = function () {
var store = new Array(8);
for (var i = 0; i < store.length; i++) {
store[i] = new Object();
store[i].next = null;
}
this.store = store;
}
MyHashMap.prototype.hash = function (i) {
return i % this.store.length;
}
MyHashMap.prototype.set = function (key, val) {
var index = this.hash(key);
var quene = this.store[index];
while (quene.next) {
if (quene.next.key === key) {
quene.next.val = val;
return;
} else {
quene = quene.next;
}
}
quene.next = {
key: key,
val: val,
next: null
}
}
MyHashMap.prototype.get = function (key) {
var index = this.hash(key);
var quene = this.store[index];
while (quene) {
if (quene.key === key) {
return quene.val;
} else {
quene = quene.next;
}
}
return undefined;
}
MyHashMap.prototype.has = function (key) {
return !!this.get(key)
}
var map = new MyHashMap();
map.set(1,'a');
map.set(2,'b');
map.set(3,'c');
map.set(4,'d');
map.set(5,'e');
map.set(6,'f');
map.set(7,'g');
map.set(8,'h');
map.set(9,'e');
console.log(map);
console.log(map.get(1))function MyHashMap() {
this.init();
}
MyHashMap.prototype.init = function () {
var store = new Array(8);
for (var i = 0; i < store.length; i++) {
store[i] = new Object();
store[i].next = null;
}
this.store = store;
}
MyHashMap.prototype.hash = function (i) {
return i % this.store.length;
}
MyHashMap.prototype.set = function (key, val) {
var index = this.hash(key);
var quene = this.store[index];
while (quene.next) {
if (quene.next.key === key) {
quene.next.val = val;
return;
} else {
quene = quene.next;
}
}
quene.next = {
key: key,
val: val,
next: null
}
}
MyHashMap.prototype.get = function (key) {
var index = this.hash(key);
var quene = this.store[index];
while (quene) {
if (quene.key === key) {
return quene.val;
} else {
quene = quene.next;
}
}
return undefined;
}
MyHashMap.prototype.has = function (key) {
return !!this.get(key)
}
var map = new MyHashMap();
map.set(1,'a');
map.set(2,'b');
map.set(3,'c');
map.set(4,'d');
map.set(5,'e');
map.set(6,'f');
map.set(7,'g');
map.set(8,'h');
map.set(9,'e');
console.log(map);
console.log(map.get(1))
console.log(map.get(8))
标签:Map,set,map,实现,quene,next,key,store,底层
From: https://www.cnblogs.com/brujie/p/16708057.html