array.ts 873 B

12345678910111213141516171819202122
  1. /**
  2. * Returns the index of the last element in the array where predicate is true, and -1
  3. * otherwise.
  4. * @param array The source array to search in
  5. * @param predicate find calls predicate once for each element of the array, in descending
  6. * order, until it finds one where predicate returns true. If such an element is found,
  7. * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
  8. */
  9. export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number {
  10. let l = array.length
  11. while (l--) {
  12. if (predicate(array[l], l, array)) {
  13. return l
  14. }
  15. }
  16. return -1
  17. }
  18. export function findLast<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {
  19. const index = findLastIndex(array, predicate)
  20. return index === -1 ? undefined : array[index]
  21. }