I often call a search call (given the page number and page size, it calculates the start, end and summary pages), and I migrated this little function from Java to help:
def page(page: Int, pageSize: Int, totalItems: Int) = { val from = ((page - 1) * pageSize) + 1 var to = from + pageSize - 1 if (to > totalItems) to = totalItems var totalPages: Int = totalItems / pageSize if (totalItems % pageSize > 0) totalPages += 1 (from, to, totalPages) }
And on the receiving side:
val (from, to, totalPages) = page(page, pageSize, totalItems)
Although it works, I'm sure there are more readable and functional ways to do the same in Scala. What will be the scala approach?
In particular, I am trying to find a more convenient way to say:
var to = from + pageSize - 1 if (to > totalItems) to = totalItems
In Java, I could do something like:
from + pageSize - 1 + (to > totalItems) ? 1 : 0;
source share