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?
-
3Actually, JSON is just a serializing format.pimvdb– pimvdb2012年02月17日 20:00:17 +00:00Commented Feb 17, 2012 at 20:00
-
Are the keys all primitives? I.e., can all keys be converted into strings correctly?pimvdb– pimvdb2012年02月17日 20:03:29 +00:00Commented Feb 17, 2012 at 20:03
-
yes, keys are strings and intsElad Benda– Elad Benda2012年02月17日 20:08:27 +00:00Commented Feb 17, 2012 at 20:08
-
@pimvdb I was asking because his question looked like he didn't, and if he didn't I would have explain it in an answer.Incognito– Incognito2012年02月17日 21:59:46 +00:00Commented Feb 17, 2012 at 21:59
2 Answers 2
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.
2 Comments
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.
3 Comments
Object.keys(obj).length.Explore related questions
See similar questions with these tags.