UNPKG

react-elegant-ui

Version:

Elegant UI components, made by BEM best practices for react

63 lines (62 loc) 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findIndexLoop = void 0; // 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 */ 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; }; exports.findIndexLoop = findIndexLoop;