Groovy web console

subscribe to the feed Subscribe
to this
site
PaginateableList (via #groovywebconsole)
tweet this snippet Tweet
this
script

PaginateableList

Published 7 years ago by Colin Harrington with tags List Category Pagination
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts

@Category(List)
class PaginateableList {
    
    List paginate(max, offset=0 ) {
        this.subList( Math.min( offset as Integer, this.size() ), Math.min( (offset as Integer) + (max as Integer), this.size() ) )
    }
}


use(PaginateableList) {    
    def list = (1..30).toList()
    assert list == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
    assert list.paginate( 5, 7 ) == [8, 9, 10, 11, 12]
    assert list.paginate( 5 )    == [1, 2, 3, 4, 5]
    assert list.paginate( 5, 0 ) == [1, 2, 3, 4, 5]
    assert list.paginate( 5, 1 ) == [2, 3, 4, 5, 6]
    assert list.paginate( "5", 1 ) == [2, 3, 4, 5, 6]
    assert list.paginate( 5, "1" ) == [2, 3, 4, 5, 6]
    assert list.paginate( 10, 25 ) == [26, 27, 28, 29, 30]
    assert list.paginate( 100, 100 ) == []
    assert list.paginate ( 5, 31 ) == []
}