react-elegant-ui
Version:
Elegant UI components, made by BEM best practices for react
56 lines • 1.46 kB
JavaScript
// TODO: rename to `findIndex`
/**
* Complex search by array top to down or vice versa
*
* Loop search from start index until start index inclusive
*
* @param items array of items
* @param predicate callback to check suitable
* @param direction 1 to positive search, -1 to negative search
*/
export var findIndexLoop = function (items, predicate, startIndex, direction,
/**
* allow disable loop search
*/
loop) {
if (startIndex === void 0) {
startIndex = 0;
}
if (direction === void 0) {
direction = 1;
}
if (loop === void 0) {
loop = true;
}
var lastIndex = items.length - 1;
// Prevent work when index out of bound
if (startIndex > lastIndex || startIndex < 0) {
throw new Error('Array out of bounds');
}
var index = startIndex;
var iteration = 0;
var isAllowSelfCheck = true;
while (index !== startIndex || isAllowSelfCheck) {
if (index === startIndex) {
isAllowSelfCheck = false;
}
var item = items[index];
if (item !== undefined) {
var isSuitableItem = predicate(item, iteration, items);
if (isSuitableItem) return index;
}
iteration++;
index += direction;
// Reset index to opposite end by going out of bounds
if (direction === 1 && index > lastIndex) {
if (!loop) break;
index = 0;
continue;
} else if (direction === -1 && index < 0) {
if (!loop) break;
index = lastIndex;
continue;
}
}
return -1;
};