Created
October 8, 2019 06:04
-
-
Save kingsleytan/8cfa7ac8acd742fe0a969a8e7029d9ae to your computer and use it in GitHub Desktop.
This file contains 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
function hash(string, max) { | |
var hash = 0; | |
for (var i = 0; i < string.length; i++) { | |
hash += string.charCodeAt(i); | |
} | |
return hash % max; | |
} | |
function HashTable() { | |
let storage = []; | |
const storageLimit = 4; | |
this.add = function (key, value) { | |
var index = hash(key, storageLimit); | |
if (storage[index] === undefined) { | |
storage[index] = [ | |
[key, value] | |
]; | |
} else { | |
var inserted = false; | |
for (var i = 0; i < storage[index].length; i++) { | |
if (storage[index][i][0] === key) { | |
storage[index][i][1] = value; | |
inserted = true; | |
} | |
} | |
if (inserted === false) { | |
storage[index].push([key, value]); | |
} | |
} | |
} | |
this.remove = function (key) { | |
var index = hash(key, storageLimit); | |
if (storage[index].length === 1 && storage[index][0][0] === key) { | |
delete storage[index]; | |
} else { | |
for (var i = 0; i < storage[index]; i++) { | |
if (storage[index][i][0] === key) { | |
delete storage[index][i]; | |
} | |
} | |
} | |
} | |
this.lookup = function (key) { | |
var index = hash(key, storageLimit); | |
if (storage[index] === undefined) { | |
return undefined; | |
} else { | |
for (var i = 0; i < storage[index].length; i++) { | |
if (storage[index][i][0] === key) { | |
return storage[index][i][1]; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment