Changing the value of an object property (illustrated using a basic linked list)

I am working on a JavaScript Link List implementation as a beginner, and I have written the following code:

var LinkList = function () {
  this.LinkedList = {
    "Head": {}
  };
};
LinkList.prototype = {
  insert: function (element) {
    var Node = this.head();
    while (Node.hasOwnProperty("Node")) {
      Node = this.next(Node);
    }
    Node["Node"] = {
      "element": element
    };
  },
  remove: function (element) {
    var Node = this.head();
    while (Node.element != element) {
      Node = this.next(Node);
    }
    delete Node.element;
    Node = Node.Node; //overwriting Node with Node.Node
  },
  next: function (Node) {
    return Node.Node;
  },
  head: function () {
    return this.LinkedList.Head;
  },
  getList: function () {
    return this.LinkedList;
  }
};

When I perform insertions using this code, everything works fine. For example:

var myList = new LinkList();
myList.insert(1);
myList.insert(5);
myList.insert(6);
myList.insert(2);

This results in a List structure like this:

    {
    "Head": {
        "Node": {
            "element": 1,
            "Node": {
                "element": 5,
                "Node": {
                    "element": 6,
                    "Node": {
                        "element": 2
                    }
                }
            }
        }
    }
}

However, when I try to remove an element, it doesn't give me the expected result. For example, if I remove the element 5:

myList.remove(5);

{
    "Head": {
        "Node": {
            "element": 1,
            "Node": {
                "Node": {
                    "element": 6,
                    "Node": {
                        "element": 2
                    }
                }
            }
        }
    }
}

I actually want the updated List to be like this:

{
    "Head": {
        "Node": {
            "element": 1,
            "Node": {
                "element": 6,
                "Node": {
                    "element": 2
                }
            }
        }
    }
}

Does anyone have any ideas on how to solve this issue? Thank you in advance.

Answer №1

One reason for the issue is that when you assign Node = Node.Node, the next node is not being assigned as the current node. Instead, you are simply assigning Node.Node to the variable Node. As a result, you do not overwrite the current node but rather obtain only read privileges.

To overcome this and take advantage of passing references, you need to modify the property of the object that your variable is referencing. This way, you will have both read and modify privileges, so to speak.

Let me illustrate what happened in your code with a short example:

// Here we create an object
var foo = {}
  , bar;

// We assign the baz property carrying bam
foo.baz = 'bam';

// We reference foo.baz with bar
bar = foo.baz;

// Now, we expect that bar equals bam
console.log(bar); //bam

// However, in this operation, we merely assign the value boom to bar
// without modifying foo.baz
bar = 'boom';

// After modifying bar in this way, foo.baz remains as bam
console.log(bar); //boom
console.log(foo.baz) //bam?

Instead of this, I suggest using a simplified approach with a stripped-down version of the code:

var List = function () {
    this.head = {};
};
List.prototype = {
    insert: function (element) {
        var node = this.head;
        while (node.next) {
            node = node.next;
        }
        node.next = {
            "element": element
        };
    },
    remove: function (element) {

        // We start with head
        var node = this.head;

        // Basically, we assign node as the next node
        // so that we can operate on the next node instead of node itself
        // and modify its values

        // While the next node is not the one we are looking for
        while (node.next.element != element) {
            // Move to the next node
            node = node.next;
        }

        // Once we find our target, delete it
        delete node.next.element;

        // Rather than assigning to the variable node, we assign to a property
        // of the object that node is referencing
        node.next = node.next.next;
    }
};

By the way, remember to use descriptive names for your variables, properties, and other elements in your code.

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

Unable to click on the icon when modifying Mui Text Field

Utilizing the MUI Text Field component, I have successfully added a select prop to transform it into a dropdown list with values and an icon. However, I encountered an issue while attempting to change the default dropdown icon to a custom one from Figma. D ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

Browsersync in Gulp keeps triggering numerous reloads every time a file is changed

As I utilize browsersync with Gulp for running specific tasks upon file changes, I notice that each time I save a file, my terminal displays 10+ [BS] Reloading Browsers... messages and the overall performance suffers. Below is an outline of my gulpfile: ...

What is the best way to retrieve an object from a POST request using Angular AJAX calls in a NODEJS environment?

When the button is clicked, a method will be called. The code for this is as follows: .controller('templeDetailsList', function ($scope, $http, $ionicModal) { $scope.starclick = function(){ var newFav = [{ ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Determining the maximum number within an array using JavaScript

Similar Question: How can I identify the largest number in a JavaScript array? I'm facing issues with this piece of code. Despite spending some time on it, I can't seem to make it work properly. The console only shows 0 when I run it. Can som ...

Transforming Errors to JSON

Can an Exception object be converted into Json in Java 7? For example: try { //something } catch(Exception ex) { Gson gson = new Gson(); System.out.println(gson.toJson(ex)); } ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

Leveraging the power of VB.net to extract data from JSON code

Hello, I need to extract the values of 21, black jack, and tongits including their scores from the following JSON code: { "id": 1, "status": "PARTIAL", "scores": [ { "scoreCard": { "21": 0, "black jack": 0 ...

Encountering a TypeError indicating that the asterisk is not functioning as a proper function

Whenever I run my server.js file, an error keeps popping up: TypeError: routing is not a function This occurs in the following line of code: routing(app); In my routing.js file, the content looks like this: // JavaScript source code var friends = requ ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

Troubleshooting a problem with Angular routing when trying to access a specific URL using

My main objective is to enable users to view products by clicking on the item itself. For each product item displayed in main.html, the URL format is like this... <a href="/products/{{ product.id }}">{{ product.title }}</a> For instance, when ...

AngularJS: accessing remote systems - a guide

I am looking to explain my objective clearly I need guidance on how to establish a remote desktop connection from my Angular.js application to a windows application running system. The server I am using is Google App Engine. My current ideas: The Windo ...

Ignoring fields in Spray-json [Scala] - A guide on selectively omitting specific fields

Currently, I am utilizing spray-json in SCALA and would like to omit certain fields from the JSON response. What is considered the best practice in this scenario? You can find more information about SPRAY-Github here. package ru.steklopod import org.scal ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Encountering an issue when attempting to convert data to JSON in Angular 13, as the content type 'text/plain;charset=UTF-8' is not supported. This problem arises after sending data from

I've been attempting to submit a form using the following method: saveBuildcompany(): void { // @ts-ignore // @ts-ignore console.log(this.group?.value); let data2=this.group.value; let serializedForm = JSON.stringify(data2) ...

The current JSON array is unable to be deserialized (for example, [1,2,3])

I am facing a challenge with JSON data and its corresponding model. Here is the JSON data: [ [ [ { "origin": [ -15.2941064136735, -0.43948581648487, 4. ...