Паттерны проектирования
- 1 ответ
- 0 вопросов
0
Вклад в тег
var banners = [
{
url: 'a.jpg',
chance: 100,
daysWeek: '1,3,4,7'
},
{
url: 'b',
chance: 50,
daysWeek: '1,3,4,7'
},
{
url: 'c',
chance: 30,
daysWeek: '1,3,4,7'
}
];
var rotoBann = function (banners, targetId, newoptions) {
if (typeof banners == 'undefined' || banners.length == 0)
return false;
var options = {
timeout: 1000,
number: 2, //колличество выбираемых баннеров. 0 - без ограничений,
random: true
};
newoptions = newoptions || {};
for (var i in options)
options[i] = newoptions[i] || options[i];
var currentDayWeek = (new Date()).getDay();
var biggestChance = 0;
var filteredByDays = [];
for (var i in banners) {
var daysWeek = banners[i].daysWeek.split(',');
for (var i2 in daysWeek) {
if (daysWeek[i2] == currentDayWeek) {
filteredByDays.push(banners[i]);
break;
}
}
}
for (var i in filteredByDays) {
biggestChance = (filteredByDays[i].chance > biggestChance) ? filteredByDays[i].chance : biggestChance;
}
filteredByDays.sort(function (a, b) {
return b.chance - a.chance
});
var selectedBanners = [];
for (var i in filteredByDays) {
if (options.number > 0 && selectedBanners.length == options.number)
break;
if (options.number == 0 || options.number >= filteredByDays.length || filteredByDays[i].chance == biggestChance) {
selectedBanners.push(filteredByDays[i].url);
continue;
}
if (Math.round(Math.random()) * 100 < filteredByDays[i].chance / biggestChance)
selectedBanners.push(filteredByDays[i].url);
}
if (options.random)
selectedBanners.sort(function () {
return Math.round(Math.random());
});
var cS = 0;
setInterval(function () {
document.getElementById(targetId).innerHTML = '<img src="'+selectedBanners[cS]+'"/>';
cS = (cS == selectedBanners.length - 1) ? 0 : cS + 1;
}, options.timeout);
}
new rotoBann(banners, 'test');