Skip to content

Instantly share code, notes, and snippets.

@jdmorlan
Created August 23, 2016 17:51
Show Gist options
  • Select an option

  • Save jdmorlan/6f60e66b9114e1f60afce4de87d61b5d to your computer and use it in GitHub Desktop.

Select an option

Save jdmorlan/6f60e66b9114e1f60afce4de87d61b5d to your computer and use it in GitHub Desktop.
Naive Hash Table Implementation
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