-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcounters.js
More file actions
61 lines (55 loc) · 1.69 KB
/
counters.js
File metadata and controls
61 lines (55 loc) · 1.69 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Counter, Trend } from 'k6/metrics';
import { targets } from './endpoints/index.js';
// This is the set of counters and trend timers maintained
// by K6. Specifically, there is one pair corresponding to each target.
export const counters = targets.reduce((m, e) => {
m[e.target.counterName] = {
counter: new Counter('target_' + e.target.counterName + '_counter'),
timer: new Trend('target_' + e.target.counterName + '_timer'),
};
return m;
}, {});
// The total weight is simply the sum of weights assigned to each target.
const totalweight = targets.reduce((total, e) => {
return total + e.weight;
}, 0);
// Choose a random target.
export function randomTarget() {
let targetIndex = Math.floor(Math.random() * totalweight);
return select(targetIndex);
}
// The select function chooses a random target based on the weight.
function select(offset) {
let targetElement = targets.reduce(
(response, elt) => {
// Already found the right element, just return it.
if (response.offset < 0) {
return response;
}
if (response.offset - elt.weight < 0) {
return {
offset: -1,
element: elt.target,
};
}
// The element is a subsequent one, reduce the offset
// by the weight of this element.
return {
offset: response.offset - elt.weight,
element: null,
};
// This is the element. Return it, and set the offset
// to a negative number.
},
{
offset: offset,
element: null,
},
);
// This should never happen.
if (targetElement.offset != -1) {
return 'yikes!!!';
}
// Return the element (the offset is -1)
return targetElement.element;
}