← All tasksNode.js · Junior

Pagination from query params

An API receives ?page=2&limit=10, which means strings. Write paginate(items, query) that returns { data, page, limit, total, totalPages }.

The defaults are page = 1 and limit = 10. An invalid value (not an integer, below 1, not a number) is replaced with the default, and limit is capped at 100 so a client can't pull the whole table at once. A page beyond the data gives an empty data.

Tests (6)

  1. const items = Array.from({ length: 25 }, (_, i) => i + 1);
    expect(paginate(items, { page: '2', limit: '10' })).toEqual({ data: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], page: 2, limit: 10, total: 25, totalPages: 3 });
  2. const items = Array.from({ length: 25 }, (_, i) => i + 1);
    expect(paginate(items, { page: '3', limit: '10' }).data).toEqual([21, 22, 23, 24, 25]);
  3. const items = [1, 2, 3];
    expect(paginate(items, {})).toEqual({ data: [1, 2, 3], page: 1, limit: 10, total: 3, totalPages: 1 });
  4. const items = [1, 2, 3];
    expect(paginate(items, { page: 'abc', limit: '-5' })).toEqual({ data: [1, 2, 3], page: 1, limit: 10, total: 3, totalPages: 1 });
    expect(paginate(items, { page: '1.5' }).page).toBe(1);
  5. const items = Array.from({ length: 500 }, (_, i) => i);
    const result = paginate(items, { limit: '1000' });
    expect(result.limit).toBe(100);
    expect(result.data).toHaveLength(100);
  6. const result = paginate([1, 2], { page: '5', limit: '10' });
    expect(result.data).toEqual([]);
    expect(result.totalPages).toBe(1);
    expect(paginate([], {}).totalPages).toBe(0);