forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash-table.js
More file actions
67 lines (59 loc) · 1.59 KB
/
hash-table.js
File metadata and controls
67 lines (59 loc) · 1.59 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
/**
* Hash Table
*
* An associative array, that can map keys
* (strings and numbers) to values in O(1).
*
* @example
* var hash = require('path-to-algorithms/src/data-structures'+
* '/hash-table');
* var HashTable = new hash.HashTable();
*
* HashTable.put(10, 'value');
* HashTable.put('key', 10);
*
* console.log(HashTable.get(10)); // 'value'
* console.log(HashTable.get('key')); // 10
*
* HashTable.remove(10);
* HashTable.remove('key');
*
* console.log(HashTable.get(10)); // 'undefined'
* console.log(HashTable.get('key')); // 'undefined'
*
* @module data-structures/hash-table
*/
(function (exports) {
'use strict';
exports.HashTable = function HashTable() {
this.elements = [];
};
exports.HashTable.prototype.hashCode = function (str) {
var i;
var hashCode = 0;
var character;
if (str.length === 0) {
return hashCode;
}
for (i = 0; i < str.length; i += 1) {
character = str.charCodeAt(i);
/*jshint -W016 */
hashCode = ((hashCode << 5) - hashCode) + character;
hashCode = hashCode & hashCode;
/*jshint -W016 */
}
return hashCode;
};
exports.HashTable.prototype.put = function (key, value) {
var hashCode = this.hashCode(key);
this.elements[hashCode] = value;
};
exports.HashTable.prototype.get = function (key) {
var hashCode = this.hashCode(key);
return this.elements[hashCode];
};
exports.HashTable.prototype.remove = function (key) {
var hashCode = this.hashCode(key);
this.elements.splice(hashCode, 1);
};
})(typeof window === 'undefined' ? module.exports : window);