Created
February 22, 2021 04:42
-
-
Save liuwenzhuang/e528f79d3bb63538ec6fbf2885de87c3 to your computer and use it in GitHub Desktop.
use array to realize hash table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DumpMap { | |
hashTable: Array<Array<[string, any]>> | |
constructor() { | |
this.hashTable = [] | |
} | |
get(x: string) { | |
const index = hash(x) | |
const backets = this.hashTable[index] | |
if (!backets) { | |
return | |
} | |
for (let i = 0, len = backets.length; i < len; i++) { | |
const backet = backets[i] | |
if (backet[0] === x) { | |
return backet[1] | |
} | |
} | |
} | |
set(x: string, y: any) { | |
const index = hash(x) | |
if (!this.hashTable[index]) { | |
this.hashTable[index] = [] | |
} | |
this.hashTable[index].push([x, y]) | |
} | |
} | |
/** | |
* hash function | |
*/ | |
function hash(str: string) { | |
const strArr = str.split('') | |
const charCodeSum = strArr.reduce((acc: number, cur: string) => { | |
return acc + cur.charCodeAt(0) | |
}, 0) | |
return divide(charCodeSum); | |
} | |
function divide(num: number): number { | |
return Math.floor(num % 10) | |
} | |
const dmap = new DumpMap() | |
for (let i = 0; i < 100; i++) { | |
dmap.set(`element${i}`, i) | |
} | |
console.clear() | |
console.log(dmap) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment