Quellcode durchsuchen

fix(video_play): 优化加权随机选择算法

- 过滤掉权重为 0 的文件,确保它们不被选中
- 添加处理所有文件权重为 0 的情况,返回 null
- 使用 ?? 运算符替代 ||,提高代码可读性
- 优化随机选择逻辑,确保按权重比例正确选择文件
tianyunperfect vor 3 Monaten
Ursprung
Commit
0d81b9b657
1 geänderte Dateien mit 8 neuen und 4 gelöschten Zeilen
  1. 8 4
      video_play/index.html

+ 8 - 4
video_play/index.html

@@ -97,15 +97,19 @@
             methods: {
                 // 加权随机选择方法
                 getWeightedRandom(files) {
-                    const totalWeight = files.reduce((sum, file) => sum + (file.weight || 1), 0);
+                    // 过滤掉权重为0的文件,确保它们不被选中
+                    const validFiles = files.filter(file => (file.weight ?? 1) > 0);
+                    if (validFiles.length === 0) return null; // 处理所有文件权重为0的情况
+
+                    const totalWeight = validFiles.reduce((sum, file) => sum + (file.weight ?? 1), 0);
                     const random = Math.random() * totalWeight;
                     let currentSum = 0;
 
-                    for (const file of files) {
-                        currentSum += file.weight || 1;
+                    for (const file of validFiles) {
+                        currentSum += file.weight ?? 1;
                         if (random <= currentSum) return file;
                     }
-                    return files[Math.floor(Math.random() * files.length)];
+                    return validFiles[validFiles.length - 1];
                 }, async fetchFiles() {
                     const res = await axios.get('/files')
                     this.files = res.data