FIX: properly round % so they add up to 100 in polls
This commit is contained in:
parent
3a1979d03c
commit
32b6ccd622
|
@ -1,13 +1,21 @@
|
||||||
|
import evenRound from "discourse/plugins/poll/lib/even-round";
|
||||||
|
import computed from "ember-addons/ember-computed-decorators";
|
||||||
|
|
||||||
export default Em.Component.extend({
|
export default Em.Component.extend({
|
||||||
tagName: "ul",
|
tagName: "ul",
|
||||||
classNames: ["results"],
|
classNames: ["results"],
|
||||||
|
|
||||||
options: function() {
|
@computed("poll.voters", "poll.options.[]")
|
||||||
|
options() {
|
||||||
|
const options = this.get("poll.options");
|
||||||
const voters = this.get("poll.voters");
|
const voters = this.get("poll.voters");
|
||||||
|
const percentages = voters === 0 ?
|
||||||
|
Array(options.length).fill(0) :
|
||||||
|
evenRound(_.map(options, o => 100 * o.get("votes") / voters));
|
||||||
|
|
||||||
this.get("poll.options").forEach(option => {
|
options.forEach((option, i) => {
|
||||||
const percentage = voters === 0 ? 0 : Math.floor(100 * option.get("votes") / voters),
|
const percentage = percentages[i];
|
||||||
style = "width: " + percentage + "%".htmlSafe();
|
const style = new Ember.Handlebars.SafeString(`width: ${percentage}%`);
|
||||||
|
|
||||||
option.setProperties({
|
option.setProperties({
|
||||||
percentage,
|
percentage,
|
||||||
|
@ -17,6 +25,6 @@ export default Em.Component.extend({
|
||||||
});
|
});
|
||||||
|
|
||||||
return this.get("poll.options");
|
return this.get("poll.options");
|
||||||
}.property("poll.voters", "poll.options.[]")
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
// stolen from http://stackoverflow.com/a/13485888/11983
|
||||||
|
export default (percentages) => {
|
||||||
|
const off = 100 - _.reduce(percentages, (acc, x) => acc + Math.round(x), 0);
|
||||||
|
return _.chain(percentages)
|
||||||
|
.sortBy(x => Math.round(x) - x)
|
||||||
|
.map((x, i) => Math.round(x) + (off > i) - (i >= (percentages.length + off)))
|
||||||
|
.value();
|
||||||
|
};
|
Loading…
Reference in New Issue