← Wszystkie zadaniaNode.js · Junior

Paginacja z parametrów zapytania

API dostaje ?page=2&limit=10, czyli napisy. Napisz paginate(items, query), które zwraca { data, page, limit, total, totalPages }.

Domyślnie page = 1 i limit = 10. Nieprawidłowa wartość (nie całkowita, mniejsza niż 1, nie liczba) jest zastępowana domyślną, a limit ograniczony z góry do 100, żeby klient nie pobrał całej tabeli naraz. Strona poza danymi daje puste data.

Testy (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);