Skip to content

Instantly share code, notes, and snippets.

@anabastos
Created September 3, 2017 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anabastos/91e3d43b72d9c1aae749ace9f6d6c6b8 to your computer and use it in GitHub Desktop.
Save anabastos/91e3d43b72d9c1aae749ace9f6d6c6b8 to your computer and use it in GitHub Desktop.
hashtable
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