Elad Benda
Elad Benda

Reputation: 36656

nested hashtables in javascript

I want to create the following data-structure with js:

folders dictionary: folder-id(guid) : ==> pages dictionary

pages array: page-position(int) : ==> files dictionary

files dictionary: file-id(guid) : ==> file object

I want to know at each time how many items are in each collection.

How would you suggest me to implemet this in JS ?

Should I use array or object with dynamically added properties?

Upvotes: 0

Views: 2130

Answers (2)

Oybek
Oybek

Reputation: 7243

Do the classes as follows.

function HashTable() {
    var content = {};
    var count = 0;
    this.Add = function(key, value) {
        if (content.hasOwnProperty(key)) throw new Error("Key already exist");
        content[key] = value;
        count++;
    };
    this.Set = function(key, value) {
        if (!content.hasOwnProperty(key)) count++;
          content[key] = value;
    };
    this.Get = function(key) {
        if (!content.hasOwnProperty(key)) throw new Error("No such key");
        return content[key];
    };
    this.AllKeys = function() {
        var keys = [];
        for (a in content) {
            keys.push(a);
        }
        return keys;
    };
    this.Count = function() {
        return count;
    };
    this.Remove = function(key) {
        if (!content.hasOwnProperty(key)) throw new Error("No such key");
        delete content[key];
        count--;
    };
}


// Then you can use it as follows

var folders = new HashTable();
folders.Add(1, 10);
alert(folders.Count());
alert(folders.Get(1));
folders.Remove(1);
alert(folders.Count());

It gives you a more rigid and OOP approach.

Edit

This ensures that your keys are unique, gives you count at any time and accepts integers and strings as keys.

Upvotes: 2

phihag
phihag

Reputation: 287755

You can just write it out:

var folders = {
    'folder1-guid': [
        {'file1-guid': 'file1-content'},
        {'file2-guid': 'file1-content'}
    ]
};

Alternatively, create Object and Array instances and assign the properties to them.

Upvotes: 2

Related Questions