|
1 | 1 | import BinarySearchTree from '../tree/BST/binarySearchTree'; |
2 | 2 |
|
3 | | -const ARRAY_SIZE = 10; |
| 3 | +interface HashMapElement<T>{ |
| 4 | + key: string, |
| 5 | + value?: T |
| 6 | +} |
| 7 | + |
| 8 | +const ARRAY_SIZE = 1000; |
4 | 9 |
|
5 | | -export default class HashMap<T> { |
6 | | - private memory : BinarySearchTree<[string, T | null]>[] = []; |
| 10 | +export default class HashMap<T = any> { |
| 11 | + private memory : BinarySearchTree<HashMapElement<any>>[] = []; |
7 | 12 |
|
8 | 13 | public length = 0; |
9 | 14 |
|
10 | | - private compareFunction = (a:[string, T | null], |
11 | | - b:[string, T | null]): number => a[0].localeCompare(b[0]); |
| 15 | + private compareFunction = (a: { key: string }, |
| 16 | + b:HashMapElement<any>): number => a.key.localeCompare(b.key); |
12 | 17 |
|
13 | 18 | set(key: string, value: T): void { |
14 | 19 | const placeToAdd = this.hashFunction(key) % ARRAY_SIZE; |
15 | 20 | if (!this.memory[placeToAdd]) { |
16 | | - this.memory[placeToAdd] = new BinarySearchTree<[string, T | null ]>(this.compareFunction); |
| 21 | + this.memory[placeToAdd] = new BinarySearchTree<HashMapElement<any>>(this.compareFunction); |
17 | 22 | } |
18 | | - this.memory[placeToAdd].add([key, value]); |
| 23 | + this.memory[placeToAdd].add({ key, value }); |
19 | 24 | this.length += 1; |
20 | 25 | } |
21 | 26 |
|
22 | | - get(key: string): [string, T | null ] | undefined { |
| 27 | + get(key: string): HashMapElement<any> | undefined { |
23 | 28 | const positionInArray = this.hashFunction(key) % ARRAY_SIZE; |
24 | 29 | const treeInArray = this.memory[positionInArray]; |
25 | 30 | if (!treeInArray) { |
26 | 31 | return undefined; |
27 | 32 | } |
28 | | - const result = treeInArray.search([key, null]); |
| 33 | + const result = treeInArray.search({ key }); |
29 | 34 | if (!result) { |
30 | 35 | return undefined; |
31 | 36 | } |
32 | 37 | return result; |
33 | 38 | } |
34 | 39 |
|
35 | | - // eslint-disable-next-line class-methods-use-this |
36 | | - private hashFunction(key:string): number { |
37 | | - return key.length; |
| 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; |
38 | 50 | } |
39 | 51 | } |
0 commit comments