# 数据结构与算法javascript描述-散列表(下)

## 代码实现



/**

* @description 在字典中我们是用键值对来存储数据

*/

const assert = require("assert");

// 散列函数

const loseloseHashCode = (key = "") => {

let hashCode = 0;

for (let i = 0; i < key.length; i++) {

hashCode += key.charCodeAt(i);

}

return hashCode % 37;

};

class patchValue {

constructor(key, value) {

this.key = key;

this.value = value;

}

}

class HashTableLine {

constructor() {

this.table = [];

}

put(key, value) {

const position = loseloseHashCode(key);

if (this.table[position] !== undefined) {

let curIndex = position + 1

while (this.table[curIndex] !== undefined) {

curIndex++

}

this.table[curIndex] = new patchValue(key, value)

} else {

this.table[position] = new patchValue(key, value)

}

}

remove(key) {

const position = loseloseHashCode(key);

if (this.table[position] && this.table[position].key === key) {

this.table[position] = undefined;

return true;

}

let curIndex = position + 1;

while (this.table[curIndex].key !== key) {

curIndex++;

}

this.table[curIndex] = undefined

return true;

}

get(key) {

const position = loseloseHashCode(key);

if (this.table[position] && this.table[position].key === key) {

return this.table[position].value;

}

let curIndex = position + 1

while (this.table[curIndex].key !== key) {

curIndex++

}

return this.table[curIndex].value

}

getItems() {

return this.table;

}

}

// test case

const hashTable = new HashTableLine();

hashTable.put("Donnie", "Donnie@qq.com");

hashTable.put("Ana", "Ana@qq.com");

console.log(hashTable.getItems());

hashTable.remove("Donnie");

hashTable.remove("Ana");

console.log(hashTable.getItems());

hashTable.put("Donnie", "Donnie@qq.com");

console.log(hashTable.getItems());



## 线性探测法 VS 分离链接法



## 参考资料

### References

[1]

[2]