I am eager to incorporate a hashtable in my JavaScript code, but unfortunately, I am encountering an unexpected

function MyHashTable(){
    var totalSize = 0;
    var dataEntry = new Object();
    this.addItem = function(key, value){
        if(!isKeyPresent(key)){
            totalSize++;
        }
        dataEntry[key] = value;
    }

    this.fetchValue = function(key){
        return isKeyPresent(key) ? dataEntry[key] : null;
    }

    this.deleteItem = function(key){
        if (isKeyPresent(key) && delete dataEntry[key]) {
            totalSize--;
        }
    }

    this.isKeyPresent = function(key){
        return (key in dataEntry);
    }

    this.isValuePresent = function(value){
        for(var prop in dataEntry){
            if(dataEntry[prop] == value){
                return true;
            }
        }
        return false;
    }

    this.getAllValues = function(){
        var values = new Array();
        for(var prop in dataEntry){
            values.push(dataEntry[prop]);
        }
        return values;
    }

    this.getAllKeys = function(){
        var keys = new Array();
        for(var prop in dataEntry){
            keys.push(prop);
        }
        return keys;
    }

    this.getSize = function(){
        return totalSize;
    }

    this.clearAll = function(){
        totalSize = 0;
        dataEntry = new Object();
    }
}

var myHashTableExample = new MyHashTable();
myHashTableExample.addItem('name', 'John');

I am trying to create a custom hash table in JavaScript but when I run a test, I encounter an error message:

Uncaught ReferenceError: containsKey is not defined at MyHashTable.addItem (:8:3) at :64:10

Answer №1

The issue at hand pertains to the concept of scope in JavaScript. The problem arises when the JavaScript interpreter is uncertain about which containsKey function to refer to within the HashTable class.

It is crucial to specify the scope when calling functions within a class by using "this". For instance, containsKey should be called as this.containsKey(key) to ensure that the interpreter understands that you are referring to the class scope rather than the local scope.

Similarly, it is advisable to prefix variables with "this" to indicate class scope. For example, instead of using size++, it is recommended to utilize this.size++. Failing to use "this" could result in the interpreter treating the function or variable as local to the function itself.

Here's a revised version of your add() function:

this.add = function(key, value){
        if(!this.containsKey(key)){
            this.size++;
        }
        this.entry[key] = value;
    }

Additionally, consider using an array for "entry" and accessing its size as this.entry.size instead of manually managing size.

To simplify the hashmap implementation, you can create two arrays within the object for keys and values, allowing you to leverage built-in JavaScript array functions for more efficiency. Each key and value will share the same index, ensuring easy correlation between them. Here is a modified example:

function HashTable() {
  this.keys = new Array();
  this.values = new Array();

  this.add = function(key, value) {

    if (this.containsKey(key)) {
      var index = this.keys.indexOf(key);
      this.values[index] = value;
    } else {
      this.keys.push(key);
      this.values.push(value);
    }
  }

  this.containsKey = function(key) {
    return this.keys.includes(key);
  }

  // More functions for handling keys, values, and size

}

// Additional code snippets for utilizing the HashTable class comes here.

Answer №2

Opt for using this.containsKey instead of containsKey since containsKey is a method specific to the object created by HashTable and should be referenced using this.

function HashTable(){
    var size = 0;
    var entry = new Object();
    
    this.containsValue = function(value){
        for(var prop in entry){
            if(entry[prop] == value){
                return true;
            }
        }
        return false;
    }
    
    this.add = function(key,value){
        if(!this.containsKey(key)){
            size++;
        }
        entry[key] = value;
    }

this.getValue = function(key){
    return this.containsKey(key)?entry[key]:null;
}

this.remove = function(key){
    if (this.containsKey(key) && delete entry[key]) {
        size--;
    }
}

this.containsKey = function(key){
    return (key in entry);
}


//get all values
    this.getValues = function(){
        var values = new Array();
        for(var prop in entry){
            values.push(entry[prop]);
        }
        return values;
    }
//get all keys
    this.getKeys = function(){
        var keys = new Array();
        for(var prop in entry){
            values.push(prop);
        }
        return keys;
    }
this.getSize = function(){
    return size;
}

this.clear = function(){
    size = 0;
    entry = new Object;//???????????????????
}
}

var hashtest = new HashTable(); hashtest.add('name','LiMing');
console.log(hashtest.getValues())

One can enhance code structure using ES6:

class HashTable {
  constructor() {
    this.size = 0;
    this.entry = new Object();
  }
  
  containsValue(value) {
    for(var prop in entry){
      if(this.entry[prop] == value){
        return true;
      }
    }
    return false;
  }
  
  add(key,value) {
    if(!this.containsKey(key)){
      this.size++;
    }
    this.entry[key] = value;
  }
  
  getValue(key) {
    return this.containsKey(key) ? this.entry[key] : null;
  }
  
  remove(key) {
    if (this.containsKey(key) && delete this.entry[key]) {
      size--;
    }
  }
  
  containsKey(key) {
    return (key in this.entry);
  }
  
  //get all values
  getValues() {
    var values = new Array();
    for(var prop in this.entry){
      values.push(this.entry[prop]);
    }
    return values;
  }
  
  //get all keys
  getKeys() {
    var keys = new Array();
    for(var prop in this.entry){
      values.push(prop);
    }
    return keys;
  }
  
  getSize() {
    return this.size;
  }
  
  clear() {
    this.size = 0;
    this.entry = new Object();//???????????????????
  }
  
}


var hashtest = new HashTable(); hashtest.add('name','LiMing');
console.log(hashtest.getValues())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate to the next page in Angular ui-grid when the down key is pressed on the last row of the grid

Is there a way to navigate to the next page if the down key is pressed in the last row of the grid? const gridScope = angular.element(document.getElementById("MainWrap")).scope(); gridScope.gridApi.pagination.nextPage(); What is the best method to detect ...

Despite returning an "OK" status, the jQuery Ajax Codebehind Post fails to function properly

Attempting to call a function in ASP.NET with jQuery Ajax: var params = "{'name':" + "\"" + name + "\"}"; $.ajax({ type: "POST", url: "CreateTopic.aspx/CreateNewTopic", data: params, ...

Move a Java application from a trial SAP HCP to a complete SAP HCP membership

After successfully creating a Java IoT App with Raspberry Pi running on SAP HANA HCP trial account, I am now looking to enhance its functionality within the SAP HANA Development Workbench. Is there a way to import it into the SAP HANA account with ease, o ...

Tips for utilizing the simple-peer module within a Node.js environment?

I recently started using Node.js and I'm interested in incorporating the simple-peer module into my application. However, I am struggling to understand how to implement it based on the provided documentation. Are there any resources available that can ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Traversing an object with a loop

I'm currently working on a project that involves utilizing the swapi co API. Although I've successfully fetched results from the website, I'm struggling with displaying only specific API objects, particularly array spaceships. var linkApi=" ...

Compatibility of image maps with browsers and the usage of imagemapster

Currently, I am utilizing ImageMapster to make adjustments to an image map while hovering. However, I am facing challenges with both the image map itself and the ImageMapster plugin. The issues I am encountering are: 1) Despite specifying a height and wid ...

Error message: "The getJSON call is missing a semicolon before the statement."

Can someone please explain the following. I've been searching online for a long time trying to find assistance and I think I am following all the correct steps but still receiving errors. Here is the script in question on my webpage: function GetPag ...

What are some methods for saving HTML form data locally?

Creating an HTML form and seeking a solution for retaining user data even after closing and reopening the window/tab. Utilizing JavaScript cookies or HTML 5 local storage would require writing code for every input tag, which could be time-consuming especi ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Error message: When using the Semantic UI React Modal, the Portal.render() function requires a valid React element to be returned, otherwise

Currently, I am working on integrating the Semantic UI React modal into my dashboard application built using React. To facilitate this integration, I have developed a ModalManager component that will be utilized in conjunction with Redux to handle the stat ...

Troubleshooting the issue with mocking API and creating a regular expression to match the dynamic part of a URL

I am struggling to create a mock for an API that includes dynamic parts in the URL. I attempted to use a regular expression, but it is not functioning as expected. The URL I am trying to mock is: https://example.com/programs/2fcce6e3-07ec-49a9-9146-fb84fb ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

The JS slider fails to function properly following the migration of AngularJS from version 1.0.8 to 1.2

Seeking assistance with migrating AngularJS from version 1.0.8 to 1.2 and encountering issues with a JavaScript slider that is no longer functioning post-migration... After upgrading to 1.2, added the angular-route.js library and injected 'ngRoute&ap ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Struggling to send data to child components in Vue: Received an object instead of the expected string value of "[object Object]"

My goal is to create a basic To-Do app where, upon clicking the button <b-button v-on:click="newItem" pill variant="primary">Add</b-button>, the input text is displayed below. To achieve this, I am using v-model in the input field (located in ...

What is the best way to handle a select input that may have varying options in

I'm struggling to figure out how to make each select input independent of each other when rendering them through a map function. How can I correctly implement this, especially considering that the data will be coming from a redux store in the future? ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...