15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 权重最小连接数
 */
module.exports = function (tasks, weightTotal, connectionsMap, context) {
 
  if (!tasks.length) return null;
 
  let min = tasks[0].weight, minIndex = 0, sum;
 
  const connectionsTotal = tasks.reduce((total, cur) => {
    total += (connectionsMap[cur.id] || 0);
    return total;
  }, 0);
 
  // algorithm: (weight + connections'weight) + random factor
  for (let i = 0; i < tasks.length; i++) {
    sum =
      (tasks[i].weight || 0) + (Math.random() * weightTotal) +
      (( (connectionsMap[tasks[i].id] || 0) * weightTotal ) / connectionsTotal);
    if (sum <= min) {
      min = sum;
      minIndex = i;
    }
  }
 
  context.weightIndex += 1;
  context.weightIndex %= (weightTotal + 1);
 
  return tasks[minIndex];
};