@kuzanatoliorg/algorithms
Version:
The utils package for react testing library
27 lines (26 loc) • 865 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.binarySearch = void 0;
const defaultComparator = (prev, curr) => prev === curr ? 0 : prev > curr ? 1 : -1;
const binarySearch = (arr, value, comparator = defaultComparator, order = true) => {
let first = 0, last = arr.length - 1, middle = Math.floor((last - first) / 2);
while (true) {
const val = order
? comparator(arr[middle], value)
: comparator(value, arr[middle]);
if (val === 0) {
return arr[middle];
}
else if (last - first <= 0) {
return null;
}
else if (val > 0) {
last = middle - 1;
}
else {
first = middle + 1;
}
middle = first + Math.floor((last - first) / 2);
}
};
exports.binarySearch = binarySearch;