Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hashtable Implementation In javascript #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions hashtable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* A hashtable is an advanced datastructure that makes use of another data structure to store values. Please not that this is a simple case, you should use something like a linked list instead of an array. You can run the demo on https://jsfiddle.net/uk1tqgnk/12/
*/

class HashTable {

/**
*
* @param {*} size size of the hashtable
*/
constructor (size) {
this.hashTableSize = size
this.buckets = new Array(size)
}

/**
*
* @param {*} key - the key to hash
* @param {*} value - value to store
*/
set (key, value) {
var index = this.hash(key)
this.buckets[index] = value
}

/**
*
* @param {*} key - key we hashed initially
*/
get (key) {
const hash = this.hash(key)
console.log(hash)
return this.buckets[hash]
}

hash (key) {
var hash = 0;
if (key.length == 0) return hash;
for (var i = 0; i < key.length; i++) {
hash = (hash<<5) - hash;
hash = hash + key.charCodeAt(i);
hash = hash & hash;
}
return Math.abs(hash);
}
}

const h = new HashTable(4)
h.set('PI',3.142)
h.set('feeling','Happy')
console.log(h.get('PI'))