Skip to content

Commit b2d74e1

Browse files
crisbetojelbourn
authored andcommitted
refactor(drag-drop): remove usages of findIndex (#12913)
Removes uses of `Array.prototype.findIndex` from `cdk/drag-drop`.
1 parent 4576863 commit b2d74e1

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/cdk/drag-drop/drop.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ export class CdkDrop<T = any> implements OnInit, OnDestroy {
218218
*/
219219
getItemIndex(item: CdkDrag): number {
220220
return this._dragging ?
221-
this._positionCache.items.findIndex(currentItem => currentItem.drag === item) :
221+
findIndex(this._positionCache.items, currentItem => currentItem.drag === item) :
222222
this._draggables.toArray().indexOf(item);
223223
}
224224

@@ -244,7 +244,7 @@ export class CdkDrop<T = any> implements OnInit, OnDestroy {
244244
}
245245

246246
const isHorizontal = this.orientation === 'horizontal';
247-
const currentIndex = siblings.findIndex(currentItem => currentItem.drag === item);
247+
const currentIndex = findIndex(siblings, currentItem => currentItem.drag === item);
248248
const siblingAtNewPosition = siblings[newIndex];
249249
const currentPosition = siblings[currentIndex].clientRect;
250250
const newPosition = siblingAtNewPosition.clientRect;
@@ -389,7 +389,7 @@ export class CdkDrop<T = any> implements OnInit, OnDestroy {
389389

390390
const isHorizontal = this.orientation === 'horizontal';
391391

392-
return this._positionCache.items.findIndex(({drag, clientRect}, _, array) => {
392+
return findIndex(this._positionCache.items, ({drag, clientRect}, _, array) => {
393393
if (drag === item) {
394394
// If there's only one item left in the container, it must be
395395
// the dragged item itself so we use it as a reference.
@@ -428,3 +428,22 @@ export class CdkDrop<T = any> implements OnInit, OnDestroy {
428428
pointerX > left - xThreshold && pointerX < right + xThreshold;
429429
}
430430
}
431+
432+
433+
/**
434+
* Finds the index of an item that matches a predicate function. Used as an equivalent
435+
* of `Array.prototype.find` which isn't part of the standard Google typings.
436+
* @param array Array in which to look for matches.
437+
* @param predicate Function used to determine whether an item is a match.
438+
*/
439+
function findIndex<T>(array: T[],
440+
predicate: (value: T, index: number, obj: T[]) => boolean): number {
441+
442+
for (let i = 0; i < array.length; i++) {
443+
if (predicate(array[i], i, array)) {
444+
return i;
445+
}
446+
}
447+
448+
return -1;
449+
}

0 commit comments

Comments
 (0)