Skip to content

Instantly share code, notes, and snippets.

@ChrisLTD
Created August 5, 2016 18:02
Show Gist options
  • Save ChrisLTD/bbc005632464b37896547e49c6829d2f to your computer and use it in GitHub Desktop.
Save ChrisLTD/bbc005632464b37896547e49c6829d2f to your computer and use it in GitHub Desktop.
'use strict';
var hashSize = 3; // small so we get collisions
var hashArray = new Array(hashSize);
var bigPrime = 1223;
function calculateHash(key) {
var hash = 0;
if(key.length > 0){
for (var i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
}
return (hash * bigPrime) % hashSize;
}
function set(key) {
var existingObj = exists(key);
if( existingObj ){
hashArray[calculateHash(key)] = {
data: key,
next: existingObj
};
}
else {
hashArray[calculateHash(key)] = {
data: key,
next: null
};
}
}
function exists(key) {
if( hashArray[calculateHash(key)] ){
return hashArray[calculateHash(key)];
}
return false;
}
function get(key) {
var existingObj = exists(key);
if(existingObj) {
return equals(key, existingObj);
}
return null;
}
function equals(key, obj) {
if(key == obj.data) {
return obj;
}
else if(obj.next) {
return equals(key, obj.next);
}
else {
return null;
}
}
// test collisions
set("chris");
set("andy");
set("william");
set("hart");
set("dubbs");
console.log(hashArray);
console.log(get("andy"));
console.log(get("dubbs"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment