javascript2016
javascript2016

Reputation: 1013

data structure association list - how to create head key value pairs?

I have a question about a data structure association list / a singly-linked list which only adds to the head. The set function is suppose to set (multiple) key-value pairs and the get function should get those pairs- I dont understand how to make the head (which is suppose to be null at first) to be an object and since the newly create node becomes the 'new' head - I dont understand how I can 'move' the 'old' head with its key value pairs.. Happy about any help! Thank you!

This is my code(not much but don't know how to go from here at all)

function List () {
 this.head=null;
}

function ListN (key, value, next) {
  this.key = key;
  this.value = value;
  this.next = next;
}
Alist.prototype.set = function (key, value) {
  // this.key=value;
  var newNode=new ListN(key, value);
  this.head=newNode;
};

Alist.prototype.get = function (key) {
  return this.key;
};

smallList = new List();

Upvotes: 1

Views: 2201

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386670

You were almost there. You missed a previous node in the call of new ListN.

var newNode = new ListN(key, value, this.head);
//                                  ^^^^^^^^^

function List() {
    this.head = null;
}

List.prototype.set = function (key, value) {

    function ListN(key, value, next) {
        this.key = key;
        this.value = value;
        this.next = next;
    }

    var node = this.head;
    while (node) {
        if (node.key === key) {
            node.value = value;
            return;
        }
        node = node.next;
    }
    this.head = new ListN(key, value, this.head);
};

List.prototype.get = function (key) {
    var node = this.head;
    while (node) {
        if (node.key === key) {
            return node.value;
        }
        node = node.next;
    }
};

var smallList = new List();

smallList.set('one', 'abc');
console.log(smallList);
smallList.set('two', 'def');
console.log(smallList);

console.log(smallList.get('one'));
console.log(smallList.get('two'));
console.log(smallList.get('three')); 

smallList.set('two', 'xyz');
console.log(smallList);

Upvotes: 1

NFRiaCowboy
NFRiaCowboy

Reputation: 303

in a key value object you should always have one key so use KISS principle:

var object = {};

object['aKey'] = 'some value';
object['otherKey] = 'other value';

If what you want is to store objects, use an array:

var myArray = [];

myArrray.push({'key': 'value'});
myArrray.push({'key': 'value'});
myArrray.push({'key1': 'value1'});

if you want a lot of values for one key:

var object = {};

if(!object.hasOwnProperty('aKey')){
  object['aKey'] = [];
}

object['aKey'].push('value');

Javascript is simple, so keep it simple :)

Upvotes: 2

Related Questions