sync/lib/poll.js

55 lines
1.5 KiB
JavaScript
Raw Normal View History

2013-12-01 23:20:42 +00:00
const link = /(\w+:\/\/(?:[^:\/\[\]\s]+|\[[0-9a-f:]+\])(?::\d+)?(?:\/[^\/\s]*)*)/ig;
var XSS = require("./xss");
2013-03-16 21:49:58 +00:00
2013-09-12 01:22:00 +00:00
var Poll = function(initiator, title, options, obscured) {
this.initiator = initiator;
2013-12-01 23:20:42 +00:00
title = XSS.sanitizeText(title);
this.title = title.replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>");
2013-03-16 21:49:58 +00:00
this.options = options;
2013-12-01 23:20:42 +00:00
for (var i = 0; i < this.options.length; i++) {
this.options[i] = XSS.sanitizeText(this.options[i]);
this.options[i] = this.options[i].replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>");
}
2013-09-12 01:22:00 +00:00
this.obscured = obscured || false;
2013-03-16 21:49:58 +00:00
this.counts = new Array(options.length);
for(var i = 0; i < this.counts.length; i++) {
this.counts[i] = 0;
}
this.votes = {};
}
Poll.prototype.vote = function(ip, option) {
if(!(ip in this.votes) || this.votes[ip] == null) {
this.votes[ip] = option;
this.counts[option]++;
}
}
Poll.prototype.unvote = function(ip) {
if(ip in this.votes && this.votes[ip] != null) {
this.counts[this.votes[ip]]--;
this.votes[ip] = null;
}
}
2013-09-12 01:22:00 +00:00
Poll.prototype.packUpdate = function (showhidden) {
var counts = Array.prototype.slice.call(this.counts);
if (this.obscured) {
for(var i = 0; i < counts.length; i++) {
if (!showhidden)
counts[i] = "";
counts[i] += "?";
}
}
var packed = {
2013-03-16 21:49:58 +00:00
title: this.title,
options: this.options,
2013-09-12 01:22:00 +00:00
counts: counts,
initiator: this.initiator
2013-09-12 01:22:00 +00:00
};
return packed;
2013-03-16 21:49:58 +00:00
}
exports.Poll = Poll;