File size: 652 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// @flow
export type PaginationOptions = {
  first: number,
  after?: string,
};

type Input = any;

type Output = {
  list: Array<Input>,
  hasMoreItems: boolean,
};

/**
 * Paginate an array
 *
 * For more complex value pass a getAfter callback to get the index of the cursor
 */
export default (
  arr: Array<Input>,
  { first, after }: PaginationOptions,
  getAfter?: any => mixed
): Output => {
  const cursor = getAfter ? arr.findIndex(getAfter) : arr.indexOf(after);
  const begin = cursor > -1 ? cursor + 1 : 0;
  const end = begin + first;
  return {
    list: arr.slice(begin, end),
    hasMoreItems: arr.length > end ? true : false,
  };
};