xref: /expo/packages/@expo/cli/src/utils/array.ts (revision dc51e206)
1/** Returns the last index of an item based on a given criteria. */
2export function findLastIndex<T>(array: T[], predicate: (item: T) => boolean) {
3  for (let i = array.length - 1; i >= 0; i--) {
4    if (predicate(array[i])) {
5      return i;
6    }
7  }
8  return -1;
9}
10
11/** Returns a list of items that intersect between two given arrays. */
12export function intersecting<T>(a: T[], b: T[]): T[] {
13  const [c, d] = a.length > b.length ? [a, b] : [b, a];
14  return c.filter((value) => d.includes(value));
15}
16
17/** lodash.uniqBy */
18export function uniqBy<T>(array: T[], key: (item: T) => string): T[] {
19  const seen: { [key: string]: boolean } = {};
20  return array.filter((item) => {
21    const k = key(item);
22    if (seen[k]) {
23      return false;
24    }
25    seen[k] = true;
26    return true;
27  });
28}
29
30/** `lodash.chunk` */
31export function chunk<T>(array: T[], size: number): T[][] {
32  const chunked = [];
33  let index = 0;
34  while (index < array.length) {
35    chunked.push(array.slice(index, (index += size)));
36  }
37  return chunked;
38}
39