Preparation of text for pagination description

Asked

Viewed 44 times

3

I have a text showing how many items are being viewed per page based on the total number of items in the database. See an image:

inserir a descrição da imagem aqui

I created an "algorithm" (which I don’t think is cool) to define in a label this text showing this data.

The function receives:

  • currentPage: Current page considering that 0 is the first page.
  • limitItensPerPage: Limit amount per page, which the database 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>
<div id="show-qnd-itens-info"></div>

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

1 answer

3


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

Assuming that this is dealt with in this function, the dial could be so:

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>
<div id="show-qnd-itens-info"></div>

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

For example:

Math.min(4, 5, 7, 2, 8); // dá 2 pois é o menor de todos
  • 1

    Good Sergio! Great solution! = D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.