-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_1_hash-table.js
More file actions
93 lines (80 loc) · 1.71 KB
/
Copy path03_1_hash-table.js
File metadata and controls
93 lines (80 loc) · 1.71 KB
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
const { performance } = require('perf_hooks');
const startingTime = performance.now();
// Start of code
class HasthTable {
constructor(length) {
this.buckets = Array(length);
this.numberOfBuckets = this.buckets.length;
}
}
class Node {
constructor(key, value, next) {
this.key = key;
this.value = value;
// In case of collisions
this.next = next || null;
}
}
// This IS not hashing
// Feel free to replace with a real hash function
HasthTable.prototype.hash = function(key) {
const abc = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'
];
const result = abc.indexOf(key[0].toLowerCase());
const bucket = result % this.numberOfBuckets;
return bucket;
};
HasthTable.prototype.add = function(key, value) {
key = key.toLowerCase();
// We only accept string
if (key.replace(/[a-z]/g, '') || key.length < 1) {
console.log('Provide a valid key!');
return;
}
const bucketIndex = this.hash(key);
// If we dont have nothing in that bucket
if (!this.buckets[bucketIndex]) {
this.buckets[bucketIndex] = new Node(key, value);
} else {
const currentNode = this.buckets[bucketIndex];
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = new Node(key, value);
}
};
// ABC > 26
let HT = new HasthTable(26);
HT.add('Casa', 'Casa Grande');
HT.add('A', 'Hello');
HT.add('Adding', 'Adding collision');
console.log(HT);
// End of code
const endingTime = performance.now();
console.log('Function took ' + (endingTime - startingTime) + ' milliseconds.');