Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Created October 15, 2017 02:32
Show Gist options
  • Save jialinhuang00/e8423f47dee5ebfeb75d75fe44ea84ac to your computer and use it in GitHub Desktop.
Save jialinhuang00/e8423f47dee5ebfeb75d75fe44ea84ac to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
the reference is from UdemyCourse: LearningDataStructuresinJavascriptFromScratch
-----------------------------------------------------------------------------*/
function HashTable(size) {
this.buckets = Array(size);
this.numBuckets = this.buckets.length;
}
function HashNode(key, value, next) {
this.key = key;
this.value = value;
this.next = next || null;
// 沒有next則給予null
}
HashTable.prototype.hash = function(key) {
var total = 0;
for (var i = 0; i < key.length; i++) {
total += key.charCodeAt(i);
}
var buckets = total % this.numBuckets;
return buckets;
// buckets [0, 29]
};
HashTable.prototype.insert = function(key, value) {
var index = this.hash(key);
// if初始化;else找到尾巴加進去
if (!this.buckets[index]) {
this.buckets[index] = new HashNode(key, value);
} else if (this.buckets[index].key === key) {
this.buckets[index].value = value;
} else {
var currentNode = this.buckets[index];
while (currentNode.next) {
if (currentNode.next.key === key) {
currentNode.next.value = value;
return;
// to stop the rest of this method from running
}
currentNode = currentNode.next;
}
currentNode.next = new HashNode(key, value);
}
};
HashTable.prototype.get = function(key) {
var index = this.hash(key);
if (!this.buckets[index]) {
return null;
} else {
var currentNode = this.buckets[index];
while (currentNode) {
if (currentNode.key === key) {
return currentNode['value'];
}
currentNode = currentNode.next;
}
return null;
}
};
// HashTable.prototype.getNode = function() {
// for (var i in this.buckets) {
// if (this.buckets[i] !== '') {
// console.log(this.buckets[i]);
// }
// }
// };
HashTable.prototype.retrieveAll = function() {
var allNode = [];
for (var i = 0; i < this.numBuckets; i++) {
var currentNode = this.buckets[i];
while (currentNode) {
allNode.push(currentNode);
currentNode = currentNode.next;
}
}
return allNode;
};
var myHT = new HashTable(30);
myHT.insert('Dean', '[email protected]');
myHT.insert('Megan', '[email protected]');
myHT.insert('Dane', '[email protected]');
myHT.insert('Dane', '[email protected]');
myHT.get('Dean');
// '[email protected]'
// return currentNode[value] 會變成 not defined
// 要寫成currentNode["value"];
// var obj = {a:['da',{dsa:12,jroe:13}], b:{}}
// obj[a]; 不行
// var a = "a"
// obj[a]; 可以
// 差別是我的子目錄指涵蓋最上頭的那一項目,而Dane在裡面。
// 官方解答除了包含我的邏輯外,還另外log出了下一層的項目。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment