function Room(modules) { function Player(key, name, alone) { this.key = key; this.name = name; this.alone = alone; this.dom = document.createElement('li'); this.dom.textContent = name; this.position = null; } var players = {}; var sortedKeys = []; var session = { key: null, loggedIn: false, selected: null }; modules.messaging.addEventListener(["Welcome"], function(o) { for(var key in o.room) { enter(parseInt(key), o.room[key]); } }); modules.messaging.addEventListener(["Update"], function(o) { o.alone.forEach(function(key) {players[key].alone = true;}); o.paired.forEach(function(key) {players[key].alone = false;}); }); modules.messaging.addEventListener(["Relay", "LogIn"], function(o) { enter(o.from, o.message); }); modules.messaging.addEventListener(["Relay", "LogOut"], function(o) { leave(o.from); }); var compareKeysByLogin = modules.sort.map(function(key) {return players[key].name;}, modules.sort.defaultCompare); return { filter: filter, enter: enter, leave: leave, name: name }; function filter(name) { if(modules.session.loggedIn()) { var keep = function(player) { return player.name.match(name) && !modules.session.is(player.key) && player.alone; }; } else { var keep = function(player) {return player.name.match(name);}; } return sortedKeys.reduce(function(accumulator, key) { var player = players[key]; return keep(player) ? accumulator.concat(player) : accumulator; }, []); } function enter(key, obj) { var name = obj.name || "anon"; var alone = obj.alone != undefined ? obj.alone : true; var player = new Player(key, name, alone); players[key] = player; player.position = modules.sort.insert(key, sortedKeys, compareKeysByLogin); sortedKeys.splice(player.position, 0, key); } function leave(key) { var player = players[key]; if(player != undefined) { sortedKeys.splice(player.position, 1); delete players[key]; } } function name(key) { player = players[key]; return player && player.name; } }