Created
September 30, 2019 01:54
-
-
Save robertDurst/b58768f04b29f512286408aeb176fa80 to your computer and use it in GitHub Desktop.
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
// started 8:00 - 8:45/9:00 (while chatting w/ friends) | |
const START_SIZE = 10; | |
const BUCKET_LIMIT = 3; | |
class HashMap { | |
constructor() { | |
this.values = new Array(START_SIZE); | |
this.count = START_SIZE; | |
this.length = START_SIZE; | |
} | |
hash(value) { | |
switch (typeof (value)) { | |
case 'number': | |
return value % this.length; | |
case 'string': | |
return value.toString() | |
.split("") | |
.reduce((sum, x) => sum + x.charCodeAt(0), 0) % this.length; | |
default: | |
throw new Error("Unexpected type. Valid types include: string, number."); | |
} | |
} | |
// if this.values is filled or if there are 3 elements in a given bucket we rebalance | |
// the values, rehashing and expanding this.values | |
rebalance() { | |
this.length = this.length ** 2; | |
this.count = this.length; | |
const valuesCopy = this.values; | |
this.values = new Array(this.length); | |
for (let bucket of valuesCopy) { | |
if (bucket) { | |
for (let slot of bucket) { | |
this.set(value); | |
} | |
} | |
} | |
} | |
// returns an element if it exists | |
// must be O(1) | |
get(value) { | |
return this.values[this.hash(value)] | |
.indexOf(value) !== -1; | |
} | |
// adds an element | |
// must be O(1) | |
set(value) { | |
const index = this.hash(value); | |
// for rebalancing, we need to know: | |
// 1. if the index's values are overflowing (3) | |
// 2. if this is the first value at an index | |
if (this.values[index]) { | |
this.values[index].push(value); | |
if (this.values[index].length === BUCKET_LIMIT) { | |
this.rebalance(); | |
} | |
} else { | |
this.values[index] = [value]; | |
this.count--; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes
this.length = this.length ** 2;
=>this.length = Math.pow(this.length, 2);
Before
After
Before
After
this.hash(value)
returns an index not in thethis.values
then this function will return an error.