Best way to download results in Scala

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; 
+4
source share
2 answers

The simplest improvement is to simply use functions instead of vars (and avoid obscuring the method name with the argument name, so it is clearer whether you call the recursive function or not):

 def pageCalc(page: Int, pageSize: Int, totalItems: Int) = { val from = ((page - 1) * pageSize) + 1 val to = totalItems min (from + pageSize - 1) val totalPages = (totalItems / pageSize) + (if (totalItems % pageSize > 0) 1 else 0) (from, to, totalPages) } 

The key changes are simply to use the min function instead of a separate var and the statement of the if to return 0 or 1, rather than updating var.

+1
source

Half of the problem is pattern identification:

 def pageCalc(page: Int, pageSize: Int, totalItems: Int) = { val pages = 1 to totalItems by pageSize val from = pages(page - 1) val to = from + pageSize - 1 min totalItems val totalPages = pages.size (from, to, totalPages) } 

Although, indeed, perhaps you could just use Range directly instead?

+8
source

Source: https://habr.com/ru/post/1332412/


All Articles