Files
discourse-data-explorer/assets/javascripts/discourse/lib/binary-search.js.es6
T

28 lines
611 B
JavaScript
Raw Normal View History

2015-08-25 20:48:19 -07:00
// The binarySearch() function is licensed under the UNLICENSE
// https://github.com/Olical/binary-search
// Modified for use in Discourse
export default function binarySearch(list, target, keyProp) {
var min = 0;
var max = list.length - 1;
var guess;
var keyProperty = keyProp || "id";
while (min <= max) {
guess = Math.floor((min + max) / 2);
2019-01-22 17:19:01 +05:30
if (Ember.get(list[guess], keyProperty) === target) {
2015-08-25 20:48:19 -07:00
return guess;
2018-10-10 17:26:23 +05:30
} else {
2019-01-22 17:19:01 +05:30
if (Ember.get(list[guess], keyProperty) < target) {
2015-08-25 20:48:19 -07:00
min = guess + 1;
2018-10-10 17:26:23 +05:30
} else {
2015-08-25 20:48:19 -07:00
max = guess - 1;
}
}
}
return -1;
}