| 160 | } |
| 161 | |
| 162 | function distributeViews(videoIds, totalViews) { |
| 163 | if (videoIds.length === 0) return []; |
| 164 | if (videoIds.length === 1) |
| 165 | return [{ videoId: videoIds[0], views: totalViews }]; |
| 166 | |
| 167 | const distribution = []; |
| 168 | let remaining = totalViews; |
| 169 | |
| 170 | for (let i = 0; i < videoIds.length - 1; i++) { |
| 171 | const maxForThis = Math.floor(remaining / (videoIds.length - i)); |
| 172 | const views = randomInt( |
| 173 | 1, |
| 174 | Math.max(1, Math.min(maxForThis, remaining - (videoIds.length - i - 1))), |
| 175 | ); |
| 176 | distribution.push({ videoId: videoIds[i], views }); |
| 177 | remaining -= views; |
| 178 | } |
| 179 | |
| 180 | if (remaining > 0) { |
| 181 | distribution.push({ |
| 182 | videoId: videoIds[videoIds.length - 1], |
| 183 | views: remaining, |
| 184 | }); |
| 185 | } else { |
| 186 | distribution.push({ videoId: videoIds[videoIds.length - 1], views: 1 }); |
| 187 | } |
| 188 | |
| 189 | return distribution; |
| 190 | } |
| 191 | |
| 192 | async function main() { |
| 193 | console.log("Fetching video IDs from database..."); |