Reputation: 75
I am creating a chat application and I ran into scaling issues. I want to create an array "roomspace" which holds multiple "room" and each room holds multiple "users". I can obviously hard code this thing but for the scale of scaling I need to declare something like roomspace[][]. But I am not being able to declare in this way and also i have been running problems while traversing the array. Can someone please give me a sample of how can this be accomplished. I would really appreciate that.
Upvotes: 0
Views: 55
Reputation: 23768
Here is a small model for you. I made the roomSpace
an object in which you can access the room by name than index.
Also you have the constructor for room object which knows how to handle a room
And the last loop demonstrates how you can traverse through the entire roomSpace
.
You can add any number of rooms and any number of users to it dynamically. You can scale this model up by adding more methods and properties.
//Your room space
var roomSpace = {};
//This function returns a room object
function constructRoom() {
return {
users: [],
addUser: function(userName) {
this.users.push(userName);
},
clearUsers: function() {
this.users = {};
}
}
}
//Here you add rooms
roomSpace['javascript'] = constructRoom();
roomSpace['php'] = constructRoom();
//Add some users
roomSpace['javascript'].addUser('charlie');
roomSpace['php'].addUser('john');
//Clear the whole room space of users
for (var room in roomSpace) {
roomSpace[room].clearUsers();
}
Upvotes: 1