Created
September 3, 2017 17:40
-
-
Save anabastos/91e3d43b72d9c1aae749ace9f6d6c6b8 to your computer and use it in GitHub Desktop.
hashtable
This file contains hidden or 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
const N = 10 | |
// const N = 127 | |
const hashTable = () => { | |
let table = [] | |
const createHashIndex = (key, colision = 0) => { | |
let hash = 0; | |
for (var i = 0; i < key.length; i++) { | |
hash = (hash << 5) - hash + key.charCodeAt(i); | |
hash = hash >>> 0; | |
} | |
return colision == 0 ? Math.abs(hash % N) : N + Math.abs(hash % (2 * N)) | |
} | |
const addToColisionArea = (hash, key) => { | |
colisionHash = createHashIndex(key, 1) | |
table[hash].colision = colisionHash | |
table[colisionHash] = { simbol: key, colision: -1 } | |
return colisionHash | |
} | |
const get = key => { | |
const value = table[key] | |
if (!value) return -1 | |
return (value.colision === -1) ? key : get(value.colision) | |
} | |
const retrieve = key => get(createHashIndex(key)) | |
return { | |
initTable: (value = []) => table = value, | |
getTable: () => table, | |
retrieve: retrieve, | |
insert: (key) => { | |
let hash = createHashIndex(key) | |
table[hash] | |
? hash = addToColisionArea(retrieve(key), key) | |
: table[hash] = { simbol: key, colision: -1 } | |
return hash | |
} | |
} | |
} | |
//funções consulta insere: | |
//simbolo, ação(consulta ou inserção), debug | |
//"break", retrieve or insert, debug | |
//caso é inserção retorna sempre a posição | |
//caso consulta sempre retorna posição ou -1 | |
// se debug == 's' | |
// imprime: Simbolo, Hashing, Posição, Ação | |
const table1 = hashTable() | |
console.log("INSERT", table1.insert("A")) | |
console.log("INSERT", table1.insert("A")) | |
console.log("RETRIEVE", table1.retrieve("A")) | |
console.log("RETRIEVE NON EXISTENT", table1.retrieve("BLA")) // -1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment