GamerPolls / gamerpolls.com

A polling site geared towards use by streamers on Twitch.
http://gamerpolls.com/
GNU General Public License v3.0
5 stars 2 forks source link

Add alternate percentage bar #13

Closed cletusc closed 10 years ago

cletusc commented 10 years ago

Show realtime percentage bars below the votes as well. Was having issues with my code not actually attaching the percentage property to the object, yet the template got it the first time around, socket.io did not. Dumping the code here for now.

Here is the code I had...

// Returns the answers array that was passed in.
function calculatePercentages(answers) {
    // Get percentage per vote.
    var scale = answers.reduce(function (prevVotes, answer) {
        return prevVotes + answer.votes;
    }, 0);
    scale = 100 / scale;

    // Calculate new percentage.
    answers = answers.map(function (answer) {
        answer.percentage = Math.round(answer.votes * scale);
        return answer;
    });
    return answers;
}

// This should go in the "vote" socket event.
$('.progress-bar[data-answer-id="' + answer._id + '"]').css('width', answer.percentage + '%');

And the html...

    <div class="progress">
        <div class="progress-bar" data-answer-id="{{_id}}" style="width: {{percentage}}%;"></div>
    </div>
cletusc commented 10 years ago

It must have something to do with it being a mongoose document. Running this code clientside works as expected; the returned array has a percentage property added to each object.

// Returns the answers array that was passed in.
function calculatePercentages(answers) {
    // Get percentage per vote.
    var scale = answers.reduce(function (prevVotes, answer) {
        return prevVotes + answer.votes;
    }, 0);
    scale = 100 / scale;

    // Calculate new percentage.
    answers = answers.map(function (answer) {
        answer.percentage = Math.round(answer.votes * scale);
        return answer;
    });
    return answers;
}

console.log(calculatePercentages([
    {votes: 7},
    {votes: 12},
    {votes: 1}
]));

Possibly related article: https://groups.google.com/forum/#!topic/mongoose-orm/lPJ6otWBDr4