add weighted random webhook pick

This commit is contained in:
Evgeny Anatskiy
2018-02-01 12:18:01 -05:00
committed by Dannon Baker
parent 6070bf07e1
commit ada76931d8
4 changed files with 24 additions and 5 deletions
+1 -1
View File
@@ -109,7 +109,7 @@ var Collection = Backbone.Collection.extend({
type: "masthead",
callback: function (webhooks) {
$(document).ready(() => {
webhooks.each((model) => {
webhooks.each(model => {
var webhook = model.toJSON();
if (webhook.activate) {
var obj = {
+21 -3
View File
@@ -20,8 +20,7 @@ const WebhookView = Backbone.View.extend({
data.reset(filterType(data, options.type));
if (data.length > 0) {
const index = _.random(0, data.length - 1);
this.render(data.at(index));
this.render(weightedRandomPick(data));
}
}
});
@@ -49,7 +48,26 @@ const load = options => {
};
function filterType (data, type) {
return _.filter(data.models, item => item.get('type').indexOf(type) !== -1);
return data.models.filter(item => item.get('type').indexOf(type) !== -1);
}
function weightedRandomPick (data) {
const weights = data.pluck('weight');
const sum = weights.reduce((a, b) => a + b);
const normalizedWeightsMap = new Map();
weights.forEach((weight, index) => {
normalizedWeightsMap.set(index, parseFloat((weight / sum).toFixed(2)));
});
const table = [];
for (const [index, weight] of normalizedWeightsMap) {
for (let i = 0; i < weight * 100; i++) {
table.push(index);
}
}
return data.at(table[Math.floor(Math.random() * table.length)]);
}
export default {
+1 -1
View File
@@ -183,7 +183,7 @@ $(document).ready(() => {
Webhooks.load({
type: "onload",
callback: function (webhooks) {
webhooks.each((model) => {
webhooks.each(model => {
var webhook = model.toJSON();
if (webhook.activate && webhook.script) {
Utils.appendScriptStyle(webhook);
+1
View File
@@ -27,6 +27,7 @@ class Webhook(object):
'id': self.id,
'type': self.type,
'activate': self.activate,
'weight': self.weight,
'styles': self.styles,
'script': self.script,
'config': self.config,