Skip to content

Commit 793086f

Browse files
committed
Merge pull request mgechev#63 from mgechev/pr/62
Hash Table data structure
2 parents fcd2b07 + 3ec53d6 commit 793086f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/data-structures/hash-table.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Hash Table
3+
*
4+
* An associative array, that can map keys
5+
* (strings and numbers) to values in O(1).
6+
*
7+
* @example
8+
* var hash = require('path-to-algorithms/src/data-structures'+
9+
* '/hash-table');
10+
* var HashTable = new hash.HashTable();
11+
*
12+
* HashTable.put(10, 'value');
13+
* HashTable.put('key', 10);
14+
*
15+
* console.log(HashTable.get(10)); // 'value'
16+
* console.log(HashTable.get('key')); // 10
17+
*
18+
* HashTable.remove(10);
19+
* HashTable.remove('key');
20+
*
21+
* console.log(HashTable.get(10)); // 'undefined'
22+
* console.log(HashTable.get('key')); // 'undefined'
23+
*
24+
* @module data-structures/hash-table
25+
*/
26+
(function (exports) {
27+
'use strict';
28+
29+
exports.HashTable = function () {
30+
this.elements = [];
31+
};
32+
33+
exports.HashTable.prototype.hashCode = function (str) {
34+
var i;
35+
var hashCode = 0;
36+
var character;
37+
38+
if (str.length === 0) {
39+
return hashCode;
40+
}
41+
42+
for (i = 0; i < str.length; i += 1) {
43+
character = str.charCodeAt(i);
44+
/*jshint -W016 */
45+
hashCode = ((hashCode << 5) - hashCode) + character;
46+
hashCode = hashCode & hashCode;
47+
/*jshint -W016 */
48+
}
49+
50+
return hashCode;
51+
};
52+
53+
exports.HashTable.prototype.put = function (key, value) {
54+
var hashCode = this.hashCode(key);
55+
this.elements[hashCode] = value;
56+
};
57+
58+
exports.HashTable.prototype.get = function (key) {
59+
var hashCode = this.hashCode(key);
60+
return this.elements[hashCode];
61+
};
62+
63+
exports.HashTable.prototype.remove = function (key) {
64+
var hashCode = this.hashCode(key);
65+
this.elements.splice(hashCode, 1);
66+
};
67+
})(typeof window === 'undefined' ? module.exports : window);

0 commit comments

Comments
 (0)