Skip to content

Commit 19105e2

Browse files
committed
Hash Table data structure
A hash table is a data structure used to implement an associative array, that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. The idea is to access a value in O(1).
1 parent fcd2b07 commit 19105e2

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

src/data-structures/hash-table.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
hashCode = ((hashCode << 5) - hashCode) + character;
45+
hashCode = hashCode & hashCode;
46+
}
47+
48+
return hashCode;
49+
};
50+
51+
exports.HashTable.prototype.put = function (key, value) {
52+
var hashCode = this.hashCode(key);
53+
this.elements[hashCode] = value;
54+
};
55+
56+
exports.HashTable.prototype.get = function (key) {
57+
var hashCode = this.hashCode(key);
58+
return this.elements[hashCode];
59+
};
60+
61+
exports.HashTable.prototype.remove = function (key) {
62+
var hashCode = this.hashCode(key);
63+
this.elements.splice(hashCode, 1);
64+
};
65+
})(typeof window === 'undefined' ? module.exports : window);

0 commit comments

Comments
 (0)