Reputation: 36656
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
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