Quick actions

cmd+k|ctrl+k

Navigation

Languages

HashTables

Snippet info

Language

JavaScript

Visibility

public

Author

psleung94

Created

2020-06-03T02:29:36Z

Updated

2020-07-28T21:28:07Z

class HashTable
{
    constructor(size)
    {
        this.data = new Array(size);
    }
    //Time complexity
    //O(1)
    _hash(key)
    {
        let hash = 0;
        for(let i = 0; i < key.length; i++)
        {
            hash = (hash + key.charCodeAt(i) * i) % this.data.length;
        }
        return hash;
    }
    //Time complexity
    //O(1)
    set(key,value)
    {
        let address = this._hash(key);
        if(!this.data[address])
        {
            this.data[address] = [];
        }
        this.data[address].push([key,value]);
        return this.data;
        
    }
    //Time complexity
    //O(1) 
    //O(n) if there are collisions
    get(key)
    {
        let address = this._hash(key);
        const currentBucket = this.data[address];
        if(currentBucket)
        {
            for(let i = 0; i < currentBucket.length; i++)
            {
                if(currentBucket[i][0] === key)
                {
                    return currentBucket[i][1];
                }
            }
        }
        return undefined;
    }
    keys()
    {
        if(!this.data.length)
        {
            return undefined;
        }
        const keysArray = [];
        for(let i = 0; i < this.data.length;i++)
        {
            if(this.data[i])//if data exists
            {
                keysArray.push(this.data[i][0][0]);
            }
        }
        return keysArray;
    }
}
const myHashTable = new HashTable(100);
myHashTable.set("grapes",5);
myHashTable.set("apples",12);
myHashTable.set("pears",20);
console.log(myHashTable.get("grapes"));
console.log(myHashTable.keys());
INFO