Created
August 23, 2016 17:51
-
-
Save jdmorlan/6f60e66b9114e1f60afce4de87d61b5d to your computer and use it in GitHub Desktop.
Naive Hash Table Implementation
This file contains hidden or 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
| const hashFunc = (str) => { | |
| let hash = 0; | |
| if (str.length === 0) return hash | |
| for (let i = 0; i < str.length; i++) { | |
| const char = str.charCodeAt(i) | |
| hash = ((hash<<5)-hash)+char | |
| hash = hash & hash | |
| } | |
| return hash | |
| } | |
| const createHash = () => { | |
| this.items = [] | |
| const addItem = (key, value) => { | |
| const index = hashFunc(key) | |
| this.items[index] = value | |
| } | |
| const getItem = (key) => { | |
| const index = hashFunc(key) | |
| return this.items[index] | |
| } | |
| const setItem = (key, value) => { | |
| const index = hashFunc(key) | |
| this.items[index] = value | |
| } | |
| const deleteItem = (key) => { | |
| const index = hashFunc(key) | |
| this.items.splice(index, 1) | |
| } | |
| return { | |
| items: this.items, | |
| add: (key, value) => addItem(key, value), | |
| get: (key) => getItem(key), | |
| set: (key, value) => setItem(key, value), | |
| delete: (key) => deleteItem(key) | |
| } | |
| } | |
| const hash = createHash() | |
| hash.add('jay', 1) | |
| console.log(hash.get('jay')) | |
| hash.set('jay', 2) | |
| console.log(hash.get('jay')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment