Skip to content

Commit b99a977

Browse files
author
Hugo Venega
committed
Add hashmap
1 parent 778a69d commit b99a977

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

src/hashmap/hashmap.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import HashMap from './hashmap';
2+
3+
interface TestElement {
4+
n : number
5+
}
6+
describe('HashMaP', () => {
7+
let hashmap: HashMap<TestElement>;
8+
beforeEach(() => {
9+
hashmap = new HashMap <TestElement>();
10+
});
11+
12+
it('should add an element into the Hashmap', () => {
13+
hashmap.set('pepe', { n: 12 });
14+
expect(hashmap.length).toEqual(1);
15+
});
16+
it('should return the requested item', () => {
17+
hashmap.set('pepe', { n: 12 });
18+
expect(hashmap.get('pepe')).toEqual({ key: 'pepe', value: { n: 12 } });
19+
});
20+
it('should return undefined when the key not hashed', () => {
21+
expect(hashmap.get('zapallo')).toEqual(undefined);
22+
});
23+
it('returns undefined when the key collides but is not found', () => {
24+
hashmap.set('pepe', { n: 12 });
25+
expect(hashmap.get('coco')).toEqual(undefined);
26+
});
27+
});

src/hashmap/hashmap.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import BinarySearchTree from '../tree/BST/binarySearchTree';
2+
3+
interface HashMapElement<T>{
4+
key: string,
5+
value?: T
6+
}
7+
8+
const ARRAY_SIZE = 1000;
9+
10+
export default class HashMap<T = any> {
11+
private memory : BinarySearchTree<HashMapElement<any>>[] = [];
12+
13+
public length = 0;
14+
15+
private compareFunction = (a: { key: string },
16+
b:HashMapElement<any>): number => a.key.localeCompare(b.key);
17+
18+
set(key: string, value: T): void {
19+
const placeToAdd = this.hashFunction(key) % ARRAY_SIZE;
20+
if (!this.memory[placeToAdd]) {
21+
this.memory[placeToAdd] = new BinarySearchTree<HashMapElement<any>>(this.compareFunction);
22+
}
23+
this.memory[placeToAdd].add({ key, value });
24+
this.length += 1;
25+
}
26+
27+
get(key: string): HashMapElement<any> | undefined {
28+
const positionInArray = this.hashFunction(key) % ARRAY_SIZE;
29+
const treeInArray = this.memory[positionInArray];
30+
if (!treeInArray) {
31+
return undefined;
32+
}
33+
const result = treeInArray.search({ key });
34+
if (!result) {
35+
return undefined;
36+
}
37+
return result;
38+
}
39+
40+
private hashFunction(key: string): number {
41+
let hashValue = 0;
42+
const stringKey = key.toString();
43+
44+
for (let index = 0; index < stringKey.length; index += 1) {
45+
const charCode = stringKey.charCodeAt(index);
46+
hashValue += charCode;
47+
}
48+
49+
return hashValue;
50+
}
51+
}

0 commit comments

Comments
 (0)