server/www/room.js

68 lines
1.5 KiB
JavaScript
Raw Normal View History

function Room(modules) {
function Player(key, name) {
this.key = key;
this.name = name;
this.dom = modules.dom.make('li', {textContent: name});
this.position = null;
}
var players = {};
var sortedKeys = [];
var session = {
key: null,
loggedIn: false,
selected: null
};
var compareKeysByLogin = modules.fun.map(function(key) {return players[key].name;}, modules.fun.defaultCompare);
return {
filter: filter,
enter: enter,
leave: leave,
name: name,
populate: populate
};
function filter(name) {
if(modules.session.isLoggedIn()) {
var keep = function(player) {
return player.name.match(name) && !modules.session.is(player.key);
};
} else {
var keep = function(player) {return player.name.match(name);};
}
return modules.fun.mapFilter(modules.fun.of(players), keep)(sortedKeys);
}
function enter(key, name) {
if(!modules.session.is(key)) {
name = name || "anon";
var player = new Player(key, name);
players[key] = player;
player.position = modules.fun.insert(key, sortedKeys, compareKeysByLogin);
sortedKeys.splice(player.position, 0, key);
}
}
2018-04-11 13:25:24 +02:00
function populate(o) {
for(var key in o.room) {
enter(key, o.room[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;
}
2018-04-11 13:25:24 +02:00
}