您的位置:首页 > Web前端 > JavaScript

JavaScript 散列表(HashTable)

2017-06-09 17:52 267 查看
TypeScript方式实现源码

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

//  put(key,value):向散列表增加一个新的项(也能更新散列表)
//  remove(key):根据键值从散列表中移除值
//  get(key):返回根据键值检索到的特定的值
//  loseloseHashCode(key):散列函数
//  put(key):


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         // 不够完善
22         // let hash = 0;
23         // for (let i = 0; i < key.length; i++) {
24         //     hash += key.charCodeAt(i);
25         // }
26         // return hash % 37;
27         // 更好的实现方式
28         var hash = 5381;
29         for (var i = 0; i < key.length; i++) {
30             hash = hash * 33 + key.charCodeAt(i);
31         }
32         return hash % 1013;
33     };
34     return HashTable;
35 }());


散列表 HashTable
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: