A Code Kata: Pagination

Many frameworks provide support for pagination of results that come from a database. However, sometimes we need to implement this fairly common pattern.

Using TDD construct the pagination logic.

  1. Pages are numbered 1-based – e.g. 1, 2, 3, 4
  2. The user gets to choose the page size
  3. There is a default page size of 25
  4. Depending on the page we’re on, we need to know how many rows to skip in the database
  5. A default request is assumed to be for page 1
  6. We call into the pagination logic with – total records in the database, requested page number, requested page size – the latter of these can be blank to mean defaults
  7. The pagination logic returns page 1 if there are no records at all
  8. The pagination logic corrects the requested page number to bring it into range, if the selected page is out of range
  9. The pagination logic returns the definition of the page that the request implies – a page in range with its own number, page size, and number of rows to skip in the database

Example:

  • Select defaults when there are ten records – returns “Page 1, Page Size 25, Rows To Skip 0”
  • Select page 2 with page size 20 when there are 100 records – returns “Page 2, Page Size 20, Rows To Skip 20”
  • Select page 10 with page size 10 when there are 20 records – returns “Page 2, Page Size 10, Rows To Skip 10”

If you solve this, please leave a solution, in a language of your choice, including the tests, in the comments.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s