Skip to content

Commit bb8367f

Browse files
committed
Allow non-string keys in hash tables
1 parent a7da7c8 commit bb8367f

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

data_structures/hash_table.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ function HashTable(initialCapacity) {
4343
* (The hash value of the empty string is zero.)
4444
*/
4545
HashTable.prototype.hash = function (s) {
46+
if (typeof s !== 'string') s = JSON.stringify(s);
4647
var hash = 0;
4748
for (var i = 0; i < s.length; i++) {
4849
hash = ((hash << 5) - hash) + s.charCodeAt(i);

test/data_structures/hash_table.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,5 +129,15 @@ describe('Hash Table', function () {
129129
h.del('foo');
130130
assert.equal(h.get('foo'), undefined);
131131
});
132+
133+
it('should allow non-string keys', function () {
134+
var h = new HashTable();
135+
h.put(10, 5);
136+
assert.equal(h.get(10), 5);
137+
138+
var o = {a: 'foo', b: 'bar'};
139+
h.put(o, 'foo');
140+
assert.equal(h.get(o), 'foo');
141+
});
132142
});
133143

0 commit comments

Comments
 (0)