<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class HashTable {
table = {}
toStrFn(item){
if(item === null){
return 'NULL'
} else if(item === undefined){
return 'UNDEFINED'
}else if (item === 'string' || item instanceof String) {
return item
}
return JSON.stringify(item)
}
/**
* 1 对象 ===> 字符串
* 2 chartAtCode +
* 3 %
*/
hashCode(key){
const tablekey = this.toStrFn(key)
let hash = 5381
for(let i=0;i<tablekey.length;i++){
hash += (hash * 33) + tablekey.charCodeAt(i)
}
return hash % 1013
}
set(key, value){
if(key != null && value != null){
const positon = this.hashCode(key)
this.table[positon] = new ValuePair(key,value)
return true
}
return false
}
hasKey(key){
return this.table[this.hashCode(key)] != null
}
get(key){
const valuepair = this.table[this.hashCode(key)]
return valuepair == null ? undefined : valuepair.value
}
remove(key){
if(this.hasKey(key)){
delete this.table[this.hashCode(key)]
return true
}
return false
}
keys(){
return this.keyValues().map(item => item.key)
}
values(){
return this.keyValues().map(item => item.value)
}
keyValues(){
return Object.values(this.table)
}
size(){
return Object.keys(this.table).length
}
isEmpty(){
return this.size() === 0
}
clear(){
this.table = {}
}
forEach(cb){
const valuepair = this.keyValues()
for(let i = 0; i < valuepair.length; i++){
cb(valuepair[i].key, valuepair[i].value)
}
}
}
class ValuePair {
constructor(key, value){
this.key = key
this.value = value
}
}
var mymap = new HashTable();
mymap.set('name','Eric')
mymap.set('tiechui','tiechui')
mymap.set('chuitie','chuitie')
mymap.set('jack','jack')
mymap.set({a:1},'aaaa')
console.log(mymap)
// mymap.get('name')
// mymap.get({a:1})
// mymap.remove('name')
// mymap.remove({a:1})
</script>
</body>
</html>