Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*-----------------------------------------------------------------------------
- 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', 'dean@gmail.com');
- myHT.insert('Megan', 'megan@gmail.com');
- myHT.insert('Dane', 'Dane@yahoo.com');
- myHT.insert('Dane', 'Danechin@yahoo.com');
- myHT.get('Dean');
- // 'dean@gmail.com'
- // 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出了下一層的項目。
Add Comment
Please, Sign In to add comment