-
Notifications
You must be signed in to change notification settings - Fork 0
/
lineHash.ts
83 lines (65 loc) · 1.64 KB
/
lineHash.ts
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
class HashLine {
private table: any[];
private value: any[];
constructor(num: number) {
this.table = new Array(num);
this.value = [];
}
public simpleHash(data: string): number {
const H = 31;
let total = 0;
for (let i = 0; i < data.length; i++) {
total += H * data.charCodeAt(i);
}
total = total % this.table.length;
if (total < 0) {
total = this.table.length - 1;
}
return total;
}
public put(key: string) {
let pos = this.simpleHash(key);
if (this.table[pos] == undefined) {
this.table[pos] = key;
this.value[pos] = key;
} else {
while (this.table[pos] != undefined) {
++pos;
}
this.table[pos] = key;
this.value[pos] = key;
}
}
public getKey(key: string): number | undefined {
let pos = this.simpleHash(key);
if (pos > 0) {
for (let i = 0; this.table[pos] != undefined; i++) {
if (this.table[pos] === key) {
return this.value[pos];
}
}
}
}
public showDistro() {
for (const key in this.table) {
this.table[key] && console.log('key: ' + key + ' value: ' + this.value[key]);
}
}
}
const hLine = new HashLine(137);
var someNames = ["David", "Jennifer", "Donnie", "Raymond",
"Cynthia", "Mike", "Clayton", "Danny", "Jonathan"];
for (const v of someNames) {
hLine.put(v);
}
hLine.showDistro();
// key: 25 value: Raymond
// key: 26 value: Clayton
// key: 34 value: Mike
// key: 44 value: Jonathan
// key: 58 value: David
// key: 68 value: Danny
// key: 119 value: Jennifer
// key: 123 value: Donnie
// key: 126 value: Cynthia
console.log(hLine.getKey('Jennifer'));