Elaboration of text for pagination description

3

I have text that shows how many items are being viewed per page based on total items in the bank. Look at an image:

Icreatedan"algorithm" (which I am not thinking legal) to define in a label this text showing that data.

The function receives:

  • currentPage : Current page whereas 0 is the first page.
  • limitItensPerPage : Limit amount per page, which the bank returns at a time.
  • totalItens : Total amount of items the database has.

I would like to improve this "algorithm" that I did well running. See below the function:

generatePageText(1, 10, 55);

function generatePageText(currentPage, limitItensPerPage, totalItens) {
  var rows, lastItem;
  var firstItem = (currentPage + 1);
  
  // Esta condição foi criada porque o limitItensPerPage 
  // é atribuido através de um select option, e em alguns casos
  // pode haver um valor maior do que a quantidade de itens 
  if (limitItensPerPage > totalItens) {
    rows = totalItens;
    lastItem = totalItens;
  } else {
    rows = limitItensPerPage;
    lastItem = ((limitItensPerPage * firstItem) > totalItens) ? totalItens :
      limitItensPerPage * firstItem;
  }
  $('#show-qnd-itens-info').text("Mostrando itens do " +
    ((firstItem * rows) - rows + 1) + " ao " + lastItem + " de " + totalItens + ".");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="show-qnd-itens-info"></div>

Knowing that it is possible to elaborate this in several ways, how could I improve this function?

    
asked by anonymous 12.08.2017 / 22:40

1 answer

3

The logic of choosing content is not in the question. I assume that this logic has a limiter to not load wrong data from the select (if the select as you say choose large numbers too).

Based on the assumption that this is handled in this function, the display might look like this:

generatePageText(1, 10, 55);

function generatePageText(currentPage, limitItensPerPage, totalItens) {
  const inicio = Math.min(currentPage * limitItensPerPage +1, totalItens);
  const fim = Math.min((currentPage + 1) * limitItensPerPage, totalItens);

  $('#show-qnd-itens-info').text("Mostrando itens do " +
    inicio + " ao " + fim + " de " + totalItens + ".");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="show-qnd-itens-info"></div>

At most it shows "Displaying items from 55 to 55 of 55." and is based on Math.min which returns the lowest value of all the arguments it receives.

For example:

Math.min(4, 5, 7, 2, 8); // dá 2 pois é o menor de todos
    
12.08.2017 / 22:53