Created
March 11, 2019 04:28
-
-
Save Ariex/9a52f81bf83f2b053d48ee7917ee00a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original article: http://www.cnblogs.com/CodeBear/p/10508880.html | |
(()=>{ | |
class Node{ | |
constructor(name, weight){ | |
this.name = name; | |
this.weight = weight; | |
this.runtimeWeight = weight; | |
} | |
} | |
class Pool{ | |
constructor(nodes){ | |
this.nodes = nodes; | |
this.totalWeight = this.nodes.reduce((a,b)=>a+b.runtimeWeight, 0); | |
} | |
*selector(){ | |
while(true){ | |
// var currentWeight = this.nodes.map(n=>n.runtimeWeight); | |
// 1. thoose the node with largest runtimeWeight | |
var workingNode = this.nodes.reduce((a, n)=>n.runtimeWeight > a.runtimeWeight ? n : a, this.nodes[0]); | |
// 2. update the selected node's runtimeWeight by subtract the total weight (which is a statuc value of sum of all weight of each nodes) | |
workingNode.runtimeWeight -= this.totalWeight; | |
// var adjustWeight = this.nodes.map(n=>n.runtimeWeight); | |
// 3. update runtimeWeight of each node, by add its original weight onto it | |
this.nodes.forEach(n=>n.runtimeWeight += n.weight); | |
// console.log(`Request assigned to ${workingNode.name} ${currentWeight} ${adjustWeight}`); | |
yield workingNode.name; | |
} | |
} | |
} | |
var p = new Pool([new Node(1, 5), new Node(2, 1), new Node(3, 1)]).selector(); | |
var counter = [0,0,0]; | |
for(var i=0;i<7000;i++){ | |
var id = p.next().value; | |
counter[id-1] +=1; | |
} | |
console.log(counter); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment