Flexiple Logo
  1. Home
  2. Blogs
  3. JavaScript
  4. Hashmaps Using Javascript

Hashmaps Using Javascript

Author image

Harsh Pandey

Software Developer

Published on Tue Apr 23 2024

Hashmaps using JavaScript enable efficient data storage and retrieval by mapping keys to values. In JavaScript, a hashmap can be implemented using objects or the `Map` object introduced in ES6. Hashmaps facilitate quick lookup, addition, and deletion of data pairs, making them ideal for scenarios where performance is critical. Each key in a hashmap is unique and directly associated with a corresponding value, allowing for rapid data access. By leveraging hashmaps, developers can significantly optimize their code's efficiency and manage data sets more effectively.

What is a hashmap?

A hashmap is a data structure that stores key-value pairs in JavaScript. It allows for efficient retrieval, insertion, and deletion of elements by using a hash function to compute an index into an array where values are stored. Hashmaps enable quick data access by transforming keys into array indices, thereby bypassing the need for a linear search. This structure is particularly useful for managing large datasets where performance and speed are crucial. In JavaScript, objects and the Map object both serve as implementations of hashmaps, with the latter providing more features like maintaining the order of elements and allowing keys of any type.

Properties

Hashmaps in JavaScript store key-value pairs where each key is unique. They operate on the principle of associating values with keys to facilitate fast retrieval, update, and deletion operations. The efficiency of these operations in a hashmap depends largely on the hash function which maps keys to indexes in the hashmap's internal array.

Key/Value

In Hashmaps using Javascript, a fundamental characteristic is the association of keys and values. Each entry in a hashmap consists of a key and a corresponding value. The key serves as a unique identifier, allowing efficient retrieval, updating, and removal of the value associated with it.

Here is how you might typically create and manipulate a hashmap in Javascript using the Map object:

// Create a new Map
let myMap = new Map();

// Set key-value pairs in the map
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

// Retrieve a value by key
let value = myMap.get('key1');  // Returns 'value1'

// Check if a key exists
let hasKey = myMap.has('key2'); // Returns true

// Remove an entry by key
myMap.delete('key2'); // Removes the key 'key2'

// Clear all entries
myMap.clear(); // Clears the map

In Javascript, keys can be of any type—numbers, strings, or objects—making the Map object versatile for various data storage applications. The efficiency of a hashmap lies in its ability to provide fast access to the data through its keys, generally achieving constant time complexity, O(1), for add, delete, and access operations.

Hashing

Hashing is the process of converting a key into an index in the hashmap's storage array. In JavaScript, a good hash function aims to be fast, distribute keys uniformly across the hash table, and minimize collisions. Collisions occur when different keys hash to the same index, and they are typically resolved using techniques such as linear probing or separate chaining.

Here's a simple example of how to implement a basic hash function in JavaScript:

function simpleHash(key, tableSize) {
  let hash = 17;
  for (let i = 0; i < key.length; i++) {
    hash = (13 * hash * key.charCodeAt(i)) % tableSize;
  }
  return hash;
}

In this code, simpleHash takes a key and the tableSize (the size of the storage array) as arguments. The function iterates over each character in the string key, updating the hash value using a combination of the hash constant and the character's ASCII value. This example is simplistic but illustrates the fundamental concept of hashing in JavaScript hashmaps.

Collisions

Collisions occur when two keys are hashed to the same index. JavaScript manages collisions through techniques like chaining, where each index in the array stores a list of entries that hash to the same index. This allows multiple entries to exist at the same location without overwriting each other.

Example:

let hashmap = {
  1: [{key: "apple", value: "fruit"}]
};

Open Addressing

Open addressing is another collision resolution method used in hashmaps. Instead of storing multiple items at each index, this method probes the hashmap array to find the next available slot. Common probing techniques include linear probing, quadratic probing, and double hashing.

For example, with linear probing:

function findSlot(hashmap, key) {
  let index = hashFunction(key);
  while (hashmap[index] !== undefined) {
    index = (index + 1) % hashmap.length;
  }
  return index;
}

In this setup, if a collision occurs at the initial index, the next sequential index is checked until an empty slot is found, ensuring all entries are stored within the array itself.

Implementation of Hashmap Class

Implementation of Hashmap Class in JavaScript involves defining a class, creating a hash function, and implementing methods to store, retrieve, and delete entries.

Class Definition

Begin by defining a Hashmap class. The class should contain a constructor that initializes an array to store the hashed keys and their associated values.

class Hashmap {
    constructor() {
        this.storage = [];
    }
}

Hash Function

The hash function converts a key into an index in the storage array. This function must consistently map the same key to the same index and evenly distribute keys across the storage space.

hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
        hash += key.charCodeAt(i);
    }
    return hash % this.storage.length;
}

Store Entries

To store an entry, use the hash function to determine the index and then place the key-value pair at that index in the storage array.

set(key, value) {
    const index = this.hash(key);
    this.storage[index] = this.storage[index] || [];
    this.storage[index].push([key, value]);
}

Retrieve Entries

Retrieve entries by using the hash function to find the index for the key and then iterating over the bucket at that index to find the matching key.

get(key) {
    const index = this.hash(key);
    const items = this.storage[index];
    if (items) {
        for (let i = 0; i < items.length; i++) {
            if (items[i][0] === key) {
                return items[i][1];
            }
        }
    }
    return undefined;
}

Delete Entries

Delete an entry by locating the index using the hash function, then finding the key in the bucket and removing it.

delete(key) {
    const index = this.hash(key);
    const items = this.storage[index];
    if (items) {
        for (let i = 0; i < items.length; i++) {
            if (items[i][0] === key) {
                items.splice(i, 1);
                return true;
            }
        }
    }
    return false;
}

Each method ensures that the Hashmap handles collisions and maintains the efficiency of operations.

Time and Space Complexity Chart

In this section, we explore the time and space complexity chart for operations in Hashmaps using JavaScript.

Hashmaps, or objects in JavaScript, store data in key-value pairs. The key operations include insertion, deletion, access, and search.

OperationAverage Case Time ComplexityWorst Case Time ComplexitySpace Complexity
InsertionO(1)O(n)O(n)
DeletionO(1)O(n)O(n)
AccessO(1)O(n)O(n)
SearchO(1)O(n)O(n)

This table and explanations should help you understand the efficiency and potential limitations when using hashmaps in JavaScript programming.

Conclusion

In conclusion, hashmaps using JavaScript provide a highly efficient method for storing and retrieving data based on key-value pairs. This data structure optimizes performance through quick access times and simplifies complex data handling tasks. Developers rely on JavaScript hashmaps to manage associative arrays efficiently, ensuring that applications run smoothly and data interactions are executed swiftly. This tool is indispensable in software development, particularly in scenarios demanding rapid data lookup and manipulation.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.