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

28 lines
613 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) {
let min = 0;
let max = list.length - 1;
let guess;
const keyProperty = keyProp || "id";
2015-08-25 20:48:19 -07:00
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;
}