JavaScript 散列表(HashTable)

Posted 肥肥鱼与鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 散列表(HashTable)相关的知识,希望对你有一定的参考价值。

TypeScript方式实现源码

// 特性:
// 散列算法的作用是尽可能快地在数据结构中找到一个值。 在之前的章节中, 你已经知道如果
// 要在数据结构中获得一个值(使用get方法) ,需要遍历整个数据结构来找到它。如果使用散列
// 函数,就知道值的具体位置,因此能够快速检索到该值。散列函数的作用是给定一个键值,然后
// 返回值在表中的地址

// ? put(key,value):向散列表增加一个新的项(也能更新散列表)
// ? remove(key):根据键值从散列表中移除值
// ? get(key):返回根据键值检索到的特定的值
// ? loseloseHashCode(key):散列函数
// ? put(key):
技术分享
 1 /**
 2  * 散列表
 3  * @desc 与Set类相似,ECMAScript 6同样包含了一个Map类的实现,即我们所说的字典
 4  */
 5 class HashTable {
 6     private table = [];
 7     public put(key, value) {
 8         let position = HashTable.loseloseHashCode(key);
 9         console.log(position + - + key);
10         this.table[position] = value;
11     }
12     public remove(key) {
13         this.table[HashTable.loseloseHashCode(key)] = undefined;
14     }
15     public get(key) {
16         return this.table[HashTable.loseloseHashCode(key)];
17     }
18     private static loseloseHashCode(key) {
19         let hash = 0;
20         for (let i = 0; i < key.length; i++) {
21             hash += key.charCodeAt(i);
22         }
23         return hash % 37;
24     }
25 }
散列表 HashTable

 

JavaScript方式实现源码

技术分享
 1 /**
 2  * 散列表
 3  * @desc 与Set类相似,ECMAScript 6同样包含了一个Map类的实现,即我们所说的字典
 4  */
 5 var HashTable = (function () {
 6     function HashTable() {
 7         this.table = [];
 8     }
 9     HashTable.prototype.put = function (key, value) {
10         var position = HashTable.loseloseHashCode(key);
11         console.log(position + - + key);
12         this.table[position] = value;
13     };
14     HashTable.prototype.remove = function (key) {
15         this.table[HashTable.loseloseHashCode(key)] = undefined;
16     };
17     HashTable.prototype.get = function (key) {
18         return this.table[HashTable.loseloseHashCode(key)];
19     };
20     HashTable.loseloseHashCode = function (key) {
21         var hash = 0;
22         for (var i_1 = 0; i_1 < key.length; i_1++) {
23             hash += key.charCodeAt(i_1);
24         }
25         return hash % 37;
26     };
27     return HashTable;
28 }());
散列表 HashTable

以上是关于JavaScript 散列表(HashTable)的主要内容,如果未能解决你的问题,请参考以下文章

HashTable(散列表)

HashTable —— 线程安全的散列表

初识java集合——散列表(HashTable)

#yyds干货盘点#看动画学算法之:hashtable

算法:分离链表法散列表

HashTable 及应用