forked from zhoutk/js-data-struct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.js
111 lines (90 loc) · 3.08 KB
/
hashtable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/***************************************************************************
> File Name : hashtable.js
> Author : zhoutk
> Mail : zhoutk@189.cn
> Create Time : 2015-09-26 18:29
***************************************************************************/
(function(){
"use strict";
var ValuePair = require("./lib/ValuePair");
var LinkedList = require("./LinkedList");
function Hashtable(){
this.table = Object.create(null);
this._size = 0;
}
Hashtable.prototype.isEmpty = function(){
return this._size === 0;
};
Hashtable.prototype.size = function(){
return this._size;
};
Hashtable.prototype.remove = function(key){
var index = hashCode(key);
if(this.table[index] == null){
return false;
}else{
var currNode = this.table[index].getHead();
while(currNode.next){
currNode = currNode.next;
if(currNode.element.key == key){
this.table[index].remove(currNode.element);
this._size--;
return true;
}
}
return false;
}
};
Hashtable.prototype.get = function(key){
var index = hashCode(key);
if(this.table[index] == null){
return null;
}else{
var currNode = this.table[index].getHead();
while(currNode.next){
currNode = currNode.next;
if(currNode.element.key == key){
return currNode.element;
}
}
return null;
}
};
Hashtable.prototype.put = function(key, value){
var index = hashCode(key);
if(this.table[index] == null){
this.table[index] = new LinkedList();
}
var currNode = this.table[index].getHead();
while(currNode.next){ //key若已经存在,修改value值为新值
currNode = currNode.next;
if(currNode.element.key == key){
currNode.element.value = value;
break;
}
}
if(currNode.next == null && currNode.element.value != value){ //key不存在,加入新值.注意边界值
this.table[index].add(new ValuePair(key,value));
this._size++;
}
return this;
};
Hashtable.prototype.display = function(){
for(var key in this.table){
var currNode = this.table[key].getHead();
while(currNode.next){
currNode = currNode.next;
console.log(currNode.element.toString());
}
}
};
/*********************** Utility Functions ********************************/
function hashCode(key) { //霍纳算法,质数取37
var hashValue = 6011;
for (var i = 0; i < key.length; i++) {
hashValue = hashValue * 37 + key.charCodeAt(i);
}
return hashValue % 1019;
}
module.exports = Hashtable;
})();