I do result paging often (given a page number and a page size calculate start, end and total pages) and I ported 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 thing in Scala. What would be a more scala-like approach?
In particular, I'm trying to find a nicer way of saying:
var to = from + pageSize - 1
if (to > totalItems) to = totalItems
In Java I could do something like:
from + pageSize - 1 + (to > totalItems) ? 1 : 0;