File size: 1,443 Bytes
9438a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
 * Sayfalama yardımcısı: sayfa sayısı, sınırlandırma ve "…" içeren sayfa düğmeleri.
 */
function pageCount(total, perPage) {
  if (!Number.isInteger(perPage) || perPage <= 0) throw new RangeError('perPage pozitif tam sayı olmalı');
  if (total < 0) throw new RangeError('total negatif olamaz');
  return Math.max(1, Math.ceil(total / perPage));
}

function clampPage(page, count) {
  if (page < 1) return 1;
  if (page > count) return count;
  return page;
}

/** İstenen sayfanın öğeleri; sayfa numarası geçerli aralığa sıkıştırılır. */
function pageItems(items, page, perPage) {
  const count = pageCount(items.length, perPage);
  const p = clampPage(page, count);
  const start = (p - 1) * perPage;
  return items.slice(start, start + perPage);
}

/**
 * Sayfa düğmeleri: ilk ve son sayfa ile current etrafında `window` komşu her zaman görünür.
 * Tek sayfalık boşluk o sayfanın kendisiyle, daha uzun boşluk '…' ile doldurulur.
 */
function pageButtons(current, count, window = 1) {
  const pages = [];
  for (let i = 1; i <= count; i++) {
    if (i === 1 || i === count || Math.abs(i - current) <= window) pages.push(i);
  }
  const out = [];
  let prev = 0;
  for (const p of pages) {
    if (p - prev === 2) out.push(prev + 1);
    else if (p - prev > 2) out.push('…');
    out.push(p);
    prev = p;
  }
  return out;
}

module.exports = { pageCount, clampPage, pageItems, pageButtons };