javascript hashmap:HashMap的JavaScript實現

來源:互聯網
上載者:User

function hashMap(){
/**
* Map大小
*/
var size = 0;
/**
* 容器預設最大長度
*/
var length = 256
var loadfactor = 0.75;
/**
* 質數
*/
var prime = 1000000;
/**
* 對象
*/
var table = new Array(length);
/**
* 設定構建Hash質數
* @param {Object} p
*/
this.setPrime = function(p){
this.prime = p;
}
/**
* 擷取構建Hash質數
*/
this.getPrime = function(){
return this.prime;
}
/**
* 當期的Hash值計算方法
*/
this.hash = BKDRHash;
/**
* HashMap的put方法
* @param {Object} key
* @param {Object} value
*/
this.put = function(key, value){
/**
* 如果裝填因子大於0.75則重新Hash
*/
if (size / length > loadfactor) {
rehash(this);
}
var counter = 0;
var code = this.hash(key);
//如果指定位置為空白,則直接存放
if (typeof table[code] == 'undefined') {
size = size + 1;
table[code] = new Entry(key, value);
//如果指定位置不為空白並且Key值相等,則覆蓋
}
else
if (table[code].key == key) {
table[code].value == value;
}
//發生散列衝突
else {
var entry = table[code];
// 訪問Hash鏈表
while(entry.next != undefined){
entry = entry.next;
if(entry.key == key){
//覆蓋
entry.value =
value;
break;
}else if(entry.next == undefined){
//新增
entry.next = new Entry(key,value);
entry.next.prev = entry;
size = siez + 1;
break;
}
}
}
}
/**
* 通過Key從HashMap中取值
* @param {Object} key 索引值
*/
this.load = function(key){
var hashcode = this.hash(key);
if(typeof table[hashcode] != 'undefined'){
var entry = table[hashcode];
if(entry.key == key){
return entry.value;
}else {
while(entry.next!= undefined){
entry = entry.next;
if(entry.key == key){
return entry.value;
}
}
}
}
return null; 本文連結http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20121114/33820.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.