JavaScript 散列表(HashTable)

时间:2022-04-16 19:39:47

TypeScript方式实现源码

// 特性:
// 散列算法的作用是尽可能快地在数据结构中找到一个值。 在之前的章节中, 你已经知道如果
// 要在数据结构中获得一个值(使用get方法) ,需要遍历整个数据结构来找到它。如果使用散列
// 函数,就知道值的具体位置,因此能够快速检索到该值。散列函数的作用是给定一个键值,然后
// 返回值在表中的地址 //  put(key,value):向散列表增加一个新的项(也能更新散列表)
//  remove(key):根据键值从散列表中移除值
//  get(key):返回根据键值检索到的特定的值
//  loseloseHashCode(key):散列函数
//  put(key):
 /**
* 散列表
* @desc 与Set类相似,ECMAScript 6同样包含了一个Map类的实现,即我们所说的字典
*/
class HashTable {
private table = [];
public put(key, value) {
let position = HashTable.loseloseHashCode(key);
console.log('position' + '-' + key);
this.table[position] = value;
}
public remove(key) {
this.table[HashTable.loseloseHashCode(key)] = undefined;
}
public get(key) {
return this.table[HashTable.loseloseHashCode(key)];
}
private static loseloseHashCode(key) {
// 不够完善
// let hash = 0;
// for (let i = 0; i < key.length; i++) {
// hash += key.charCodeAt(i);
// }
// return hash % 37;
// 更好的实现方式
let hash = ;
for (var i = ; i < key.length; i++) {
hash = hash * + key.charCodeAt(i);
}
return hash % ;
}
}

散列表 HashTable

JavaScript方式实现源码

 /**
* 散列表
* @desc 与Set类相似,ECMAScript 6同样包含了一个Map类的实现,即我们所说的字典
*/
var HashTable = (function () {
function HashTable() {
this.table = [];
}
HashTable.prototype.put = function (key, value) {
var position = HashTable.loseloseHashCode(key);
console.log('position' + '-' + key);
this.table[position] = value;
};
HashTable.prototype.remove = function (key) {
this.table[HashTable.loseloseHashCode(key)] = undefined;
};
HashTable.prototype.get = function (key) {
return this.table[HashTable.loseloseHashCode(key)];
};
HashTable.loseloseHashCode = function (key) {
// 不够完善
// let hash = 0;
// for (let i = 0; i < key.length; i++) {
// hash += key.charCodeAt(i);
// }
// return hash % 37;
// 更好的实现方式
var hash = ;
for (var i = ; i < key.length; i++) {
hash = hash * + key.charCodeAt(i);
}
return hash % ;
};
return HashTable;
}());

散列表 HashTable