importLinkedListfrom'../linked-list/LinkedList.js';// The bigger the hash table size the less collisions you'll get.constdefaultHashTableSize=32;exportdefaultclassHashTable{constructor(hashTableSize=defaultHashTableSize){// fill each bucket with empty linked list.this.buckets=Array(hashTableSize).fill(null).map(()=>newLinkedList());this.keys={};}/** * Converts key string to hash number. * * @param {string} key * @returns {number} */hash(key){/* A simple hash function */consthash=Array.from(key).reduce((accumulator,ch)=>(accumulator+ch.charCodeAt(0)),0);returnhash%this.buckets.length;}/** * @param {string} key * @param {*} value */set(key,value){consthashKey=this.hash(key);this.keys[key]=hashKey;constbucketLinkedList=this.buckets[hashKey];constnode=bucketLinkedList.find({callback:nodeVal=>nodeVal.key===key});if(!node){// Insert new node.bucketLinkedList.append({key,value});}else{// Update value of existing node.node.value.value=value;}}/** * @param {string} key * @returns {*} */delete(key){consthashKey=this.hash(key);deletethis.keys[key];constbucketLinkedList=this.buckets[hashKey];constnode=bucketLinkedList.find({callback:nodeVal=>nodeVal.key===key});if(node){// node.value 是引用类型returnbucketLinkedList.delete(node.value);}returnnull;}get(key){constbucketLinkedList=this.buckets[this.hash(key)];constnode=bucketLinkedList.find({callback:nodeVal=>nodeVal.key===key});returnnode?node.value.value:undefined;}has(key){returnObject.hasOwnProperty.call(this.keys,key);}getKeys(){returnObject.keys(this.keys);}/** * Gets the list of all the stored values in the hash table. * * @return {*[]} */getValues(){returnthis.buckets.reduce((values,bucket)=>{constbucketValues=bucket.toArray().map((linkedListNode)=>linkedListNode.value.value);returnvalues.concat(bucketValues);},[])}}