forked from jondubois/capitalisk-interchain-old
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandomized-selection.js
40 lines (37 loc) · 1.36 KB
/
randomized-selection.js
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
31
32
33
34
35
36
37
38
39
40
const shuffle = require('lodash.shuffle');
let randomizedSelectForRequestFunction = (input) => {
let { peers } = input;
let peerLimit = input.peerLimit;
if (peers.length === 0) {
return [];
}
if (peerLimit === undefined) {
return shuffle(peers);
}
return shuffle(peers).slice(0, peerLimit);
};
let randomizedSelectForSendFunction = (input) => {
let shuffledPeers = shuffle(input.peers);
let peerLimit = input.peerLimit;
let halfPeerLimit = Math.round(peerLimit / 2);
let outboundPeers = shuffledPeers.filter((peerInfo) => peerInfo.kind === 'outbound');
let inboundPeers = shuffledPeers.filter((peerInfo) => peerInfo.kind === 'inbound');
let shortestPeersList;
let longestPeersList;
if (outboundPeers.length < inboundPeers.length) {
shortestPeersList = outboundPeers;
longestPeersList = inboundPeers;
}
else {
shortestPeersList = inboundPeers;
longestPeersList = outboundPeers;
}
let selectedFirstKindPeers = shortestPeersList.slice(0, halfPeerLimit);
let remainingPeerLimit = peerLimit - selectedFirstKindPeers.length;
let selectedSecondKindPeers = longestPeersList.slice(0, remainingPeerLimit);
return selectedFirstKindPeers.concat(selectedSecondKindPeers);
};
module.exports = {
randomizedSelectForRequestFunction,
randomizedSelectForSendFunction
};