Skip to content

Instantly share code, notes, and snippets.

@nLight
Created October 19, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nLight/7f7c2f475b715f037fa44b57ec7585f1 to your computer and use it in GitHub Desktop.
Save nLight/7f7c2f475b715f037fa44b57ec7585f1 to your computer and use it in GitHub Desktop.
Javascript Hash Table
function hash(string) {
let index = 0;
for(let i = 0; i < string.length; i++) {
index += string.charCodeAt(i) * i;
}
return index % _size;
}
function HashTable(size) {
const _size = size;
const _store = [];
function hash(string) {
let index = 0;
for(let i = 1; i <= string.length; i++) {
index += string.charCodeAt(i) * i;
}
return index % _size;
}
return {
setElement(key, element){
if(!_store[hash(key)] || _store[hash(key)] && _store[hash(key)][0] === key) {
_store[hash(key)] = [key, element];
}
else {
throw new Error("Collision!");
}
},
getElement(key){
if(_store[hash(key)]) {
return _store[hash(key)][1];
}
return;
}
};
}
function HashTable(size) {
const _store = [];
const _size = size;
function hash(string) {
let index = 0;
for(let i = 0; i < string.length; i++) {
index += string.charCodeAt(i) * i + 1;
}
return index % _size;
}
function findMatchIndex(list, key) {
for(let i = 0; i < list.length; i++) {
if(list[i][0] === key) return i;
}
}
return {
dump() {
console.dir(_store);
},
setElement(key, element){
if(!_store[hash(key)]) {
_store[hash(key)] = [
[key, element]
];
}
else {
const list = _store[hash(key)];
const index = findMatchIndex(list, key);
if(index) {
return list[index] = [key, element];
}
list.push([key, element]);
}
},
getElement(key){
if(_store[hash(key)]) {
const list = _store[hash(key)];
const index = findMatchIndex(list, key);
if(index) return list[index][1]
}
return;
}
};
}
function HashTable(size = 10) {
const _size = size;
const _store = [];
function hash(string) {
return string.length % _size;
}
return {
setElement(key, element) {
_store[hash(key)] = element;
},
getElement(key){
return _store[hash(key)];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment