Skip to content

Commit 6b7c99b

Browse files
authored
Merge pull request #2395 from murgatroid99/grpc-js-xds_weighted_target_simple_1.8.x
grpc-js-xds: Use simpler search algorithm in weighted target picker
2 parents 9264d58 + e5e6731 commit 6b7c99b

File tree

1 file changed

+7
-22
lines changed

1 file changed

+7
-22
lines changed

packages/grpc-js-xds/src/load-balancer-weighted-target.ts

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -119,31 +119,16 @@ class WeightedTargetPicker implements Picker {
119119
pick(pickArgs: PickArgs): PickResult {
120120
// num | 0 is equivalent to floor(num)
121121
const selection = (Math.random() * this.rangeTotal) | 0;
122-
123-
/* Binary search for the element of the list such that
124-
* pickerList[index - 1].rangeEnd <= selection < pickerList[index].rangeEnd
125-
*/
126-
let mid = 0;
127-
let startIndex = 0;
128-
let endIndex = this.pickerList.length - 1;
129-
let index = 0;
130-
while (endIndex > startIndex) {
131-
mid = ((startIndex + endIndex) / 2) | 0;
132-
if (this.pickerList[mid].rangeEnd > selection) {
133-
endIndex = mid;
134-
} else if (this.pickerList[mid].rangeEnd < selection) {
135-
startIndex = mid + 1;
136-
} else {
137-
// + 1 here because the range is exclusive at the top end
138-
index = mid + 1;
139-
break;
122+
123+
for (const entry of this.pickerList) {
124+
if (selection < entry.rangeEnd) {
125+
return entry.picker.pick(pickArgs);
140126
}
141127
}
142-
if (index === 0) {
143-
index = startIndex;
144-
}
145128

146-
return this.pickerList[index].picker.pick(pickArgs);
129+
/* Default to first element if the iteration doesn't find anything for some
130+
* reason. */
131+
return this.pickerList[0].picker.pick(pickArgs);
147132
}
148133
}
149134

0 commit comments

Comments
 (0)