Quick actions

cmd+k|ctrl+k

Navigation

Languages

HashMapCustom

Snippet info

Language

JavaScript

Visibility

public

Author

ryanlove64

Created

2019-06-03T04:17:08Z

Updated

2019-06-03T20:34:03Z

class HashTable{
    constructor(size){
        this.data=new Array(size);
    }
    
    
    _hash(key) {
       let hash = 0;
        for(let i = 0; i < key.length; i++){
            hash = (hash + key.charCodeAt(i)* i) % this.data.length;
            this.data.length;
        }
        return hash;
    }
    
     set(key, value) {
        let  address = this._hash(key);
        if(!this.data[address]){
            this.data[address] = [];
        }
        
            this.data[address].push([key,value]);
             return this.data;   
        }
         
    
    
    get(key){
    const address = this._hash(key);
    const currentBucket = this.data[address];
    console.log(currentBucket);
    if(currentBucket){
        for(let i =0; i<currentBucket.length; i++){
            if(currentBucket[i][0] === key){
            return currentBucket[i][1];
            }
        }
      }
      return undefined;
     }
     
     keys(){
         const keysArray = [];
         for(let i=0; i<this.data.length; i++){
             if(this.data[i]){
                 keysArray.push(this.data[i][0][0]);
             }
         }
         return keysArray;
     }
    
}

const myHashTable = new HashTable(50);
myHashTable.set('pears',10000);
myHashTable.set('apple',54);
myHashTable.set('grapes',50);

myHashTable.keys();
INFO