diff --git a/src/hashmap/hashmap.spec.ts b/src/hashmap/hashmap.spec.ts new file mode 100644 index 0000000..07ae9c5 --- /dev/null +++ b/src/hashmap/hashmap.spec.ts @@ -0,0 +1,30 @@ +import HashMap from './hashmap'; + +interface TestElement { + n : number +} +describe('HashMaP', () => { + let hashmap: HashMap; + beforeEach(() => { + hashmap = new HashMap (); + }); + + 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); + }); +}); diff --git a/src/hashmap/hashmap.ts b/src/hashmap/hashmap.ts new file mode 100644 index 0000000..63a43ac --- /dev/null +++ b/src/hashmap/hashmap.ts @@ -0,0 +1,51 @@ +import BinarySearchTree from '../tree/BST/binarySearchTree'; + +interface HashMapElement{ + key: string, + value?: T +} + +const ARRAY_SIZE = 1000; + +export default class HashMap { + private memory : BinarySearchTree>[] = []; + + public length = 0; + + private compareFunction = (a: { key: string }, + b:HashMapElement): 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>(this.compareFunction); + } + this.memory[placeToAdd].add({ key, value }); + this.length += 1; + } + + get(key: string): HashMapElement | 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; + } +}