forked from yanlele/node-index
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex3.js
105 lines (95 loc) · 2.67 KB
/
index3.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
class ValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
}
toString() {
return `[ ${this.key} - ${this.value} ]`
}
}
class Node {
constructor(element) {
this.element = element;
this.next = null
}
}
class LinkedList {
constructor() {
this.table = [];
this.length = 0;
this.head = null;
}
djb2(key) {
let hash = 5381;
for (let i = 0; i < key.length; i++) {
hash = hash * 33 + key.charCodeAt(i);
}
return hash % 1013;
}
append(element) {
let node = new Node(element), current;
if(this.head === null) {
this.head = node;
} else {
current = this.head;
//如果有下一项就直接移动到下一项
while (current.next) {
current = current.next;
}
//如果没有下一项,就直接填充当前项
current.next = node;
}
this.length ++;
}
getHead() {
return this.head;
}
put(key, value) {
let position = this.djb2(key);
if(this.table[position] === undefined) {
this.table[position] = new ValuePair(key ,value);
} else {
let index = ++position;
while (this.table[index] !==undefined) {
index ++;
}
this.table[index] = new ValuePair(key, value);
}
}
get(key) {
let position = this.djb2(key);
if(this.table[position] !== undefined) {
if(this.table[position].key === key) {
return this.table[position].value;
} else {
let index = ++position;
while (this.table[index] === undefined || this.table[index].key !== key) {
index++
}
if(this.table[index].key === key) {
return this.table[index].value;
}
}
}
}
remove(key) {
let position = this.djb2(key);
if(this.table[position] !== undefined) {
if(this.table[position].key === key) {
this.table[position] = undefined;
return true
} else {
let index = ++position;
while (this.table[index] === undefined || this.table[index].key !== key) {
index++
}
if(this.table[index].key === key) {
this.table[index] = undefined;
return true;
}
}
}
return false;
}
}
module.exports = LinkedList;