mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add new hash table methods.
This commit is contained in:
@@ -17,7 +17,7 @@ describe('HashTable', () => {
|
||||
expect(hashTable.hash('abc')).toBe(6);
|
||||
});
|
||||
|
||||
it('should insert, read and delete data with collisions', () => {
|
||||
it('should set, read and delete data with collisions', () => {
|
||||
const hashTable = new HashTable(3);
|
||||
|
||||
expect(hashTable.hash('a')).toBe(1);
|
||||
@@ -25,11 +25,15 @@ describe('HashTable', () => {
|
||||
expect(hashTable.hash('c')).toBe(0);
|
||||
expect(hashTable.hash('d')).toBe(1);
|
||||
|
||||
hashTable.insert('a', 'sky-old');
|
||||
hashTable.insert('a', 'sky');
|
||||
hashTable.insert('b', 'sea');
|
||||
hashTable.insert('c', 'earth');
|
||||
hashTable.insert('d', 'ocean');
|
||||
hashTable.set('a', 'sky-old');
|
||||
hashTable.set('a', 'sky');
|
||||
hashTable.set('b', 'sea');
|
||||
hashTable.set('c', 'earth');
|
||||
hashTable.set('d', 'ocean');
|
||||
|
||||
expect(hashTable.has('x')).toBeFalsy();
|
||||
expect(hashTable.has('b')).toBeTruthy();
|
||||
expect(hashTable.has('c')).toBeTruthy();
|
||||
|
||||
const stringifier = value => `${value.key}:${value.value}`;
|
||||
|
||||
@@ -47,18 +51,38 @@ describe('HashTable', () => {
|
||||
expect(hashTable.get('a')).toBeNull();
|
||||
expect(hashTable.get('d')).toBe('ocean');
|
||||
|
||||
hashTable.insert('d', 'ocean-new');
|
||||
hashTable.set('d', 'ocean-new');
|
||||
expect(hashTable.get('d')).toBe('ocean-new');
|
||||
});
|
||||
|
||||
it('should be possible to add objects to hash table', () => {
|
||||
const hashTable = new HashTable();
|
||||
|
||||
hashTable.insert('objectKey', { prop1: 'a', prop2: 'b' });
|
||||
hashTable.set('objectKey', { prop1: 'a', prop2: 'b' });
|
||||
|
||||
const object = hashTable.get('objectKey');
|
||||
expect(object).toBeDefined();
|
||||
expect(object.prop1).toBe('a');
|
||||
expect(object.prop2).toBe('b');
|
||||
});
|
||||
|
||||
it('should track actual keys', () => {
|
||||
const hashTable = new HashTable(3);
|
||||
|
||||
hashTable.set('a', 'sky-old');
|
||||
hashTable.set('a', 'sky');
|
||||
hashTable.set('b', 'sea');
|
||||
hashTable.set('c', 'earth');
|
||||
hashTable.set('d', 'ocean');
|
||||
|
||||
expect(hashTable.getKeys()).toEqual(['a', 'b', 'c', 'd']);
|
||||
expect(hashTable.has('a')).toBeTruthy();
|
||||
expect(hashTable.has('x')).toBeFalsy();
|
||||
|
||||
hashTable.delete('a');
|
||||
|
||||
expect(hashTable.has('a')).toBeFalsy();
|
||||
expect(hashTable.has('b')).toBeTruthy();
|
||||
expect(hashTable.has('x')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user