Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/hashmap/hashmap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import HashMap from './hashmap';

interface TestElement {
n : number
}
describe('HashMaP', () => {
let hashmap: HashMap<TestElement>;
beforeEach(() => {
hashmap = new HashMap <TestElement>();
});

it('should add an element into the Hashmap', () => {
hashmap.set('pepe', { n: 12 });
expect(hashmap.length).toEqual(1);
});

it('should return the requested item', () => {
hashmap.set('pepe', { n: 12 });
expect(hashmap.get('pepe')).toEqual({ key: 'pepe', value: { n: 12 } });
});

it('should return undefined when the key not hashed', () => {
expect(hashmap.get('zapallo')).toEqual(undefined);
});

it('shoud return undefined when the key collides but is not found', () => {
hashmap.set('pepe', { n: 12 });
expect(hashmap.get('coco')).toEqual(undefined);
});
});
51 changes: 51 additions & 0 deletions src/hashmap/hashmap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import BinarySearchTree from '../tree/BST/binarySearchTree';

interface HashMapElement<T>{
key: string,
value?: T
}

const ARRAY_SIZE = 1000;

export default class HashMap<T = any> {
private memory : BinarySearchTree<HashMapElement<T>>[] = [];

public length = 0;

private compareFunction = (a: { key: string },
b:HashMapElement<T>): number => a.key.localeCompare(b.key);

set(key: string, value: T): void {
const placeToAdd = this.hashFunction(key) % ARRAY_SIZE;
if (!this.memory[placeToAdd]) {
this.memory[placeToAdd] = new BinarySearchTree<HashMapElement<T>>(this.compareFunction);
}
this.memory[placeToAdd].add({ key, value });
this.length += 1;
}

get(key: string): HashMapElement<T> | undefined {
const positionInArray = this.hashFunction(key) % ARRAY_SIZE;
const treeInArray = this.memory[positionInArray];
if (!treeInArray) {
return undefined;
}
const result = treeInArray.search({ key });
if (!result) {
return undefined;
}
return result;
}

private hashFunction(key: string): number {
let hashValue = 0;
const stringKey = key.toString();

for (let index = 0; index < stringKey.length; index += 1) {
const charCode = stringKey.charCodeAt(index);
hashValue += charCode;
}

return hashValue;
}
}