@sanity/form-builder
Version:
Sanity form builder
45 lines (43 loc) • 1.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.nearestIndex = nearestIndex;
exports.nearestIndexOf = nearestIndexOf;
/**
* Find the index of the nearest element with the same value. Starts at given index and looks incrementally in either direction for the searchElement
* It's *NOT* inclusive: If the element matches the element at the startIdx, startIdx will be returned
* It prefers matches in the first half. If there's a tie it will pick the first element that comes before
* @param array
* @param startIdx
* @param searchElement
*/
function nearestIndexOf(array, startIdx, searchElement) {
return nearestIndex(array, startIdx, element => element === searchElement);
}
/**
* Find the index of the nearest element matching the predicate. Starts at given index and looks incrementally in either direction
* It's *NOT* inclusive: If the predicate matches the element at the startIdx, startIdx will be returned
* It prefers matches in the first half. If there's a tie it will pick the first element that comes before
* @param array
* @param startIdx
* @param predicate
*/
function nearestIndex(array, startIdx, predicate) {
var lowerIdx = startIdx - 1;
var upperIdx = startIdx;
var len = array.length;
while (lowerIdx > -1 || upperIdx < len) {
var upper = array[upperIdx];
if (upperIdx < len && predicate(upper, upperIdx)) {
return upperIdx;
}
var lower = array[lowerIdx];
if (lowerIdx > -1 && predicate(lower, lowerIdx)) {
return lowerIdx;
}
lowerIdx--;
upperIdx++;
}
return -1;
}