Pagination

by Roman Zolotarev

Recently I was working on a pagination for a web app. This simple problem can be a good case to compare JavaScript and Elm.

Table of contents

Pagination
Vanilla JavaScript
Built with Ramda
Built with Elm
Epilog

Here is the use case:

We have a current page address, e.g. index, and a list of all page addresses: index, vanilla, ramda, elm.

There are two links: Previous and Next. By clicking on those links you go to the previous or the next page accordingly.

When you are on the first page, Previous button is disabled. When on the last, Next is disabled.


              current page
                   |
                   |
 [ Previous ]    index    vanilla    ramda    elm    [ Next ]
      |
      |
disabled link

Let’s write two functions. One to prepare a data structure and another to generate HTML code based on it.

paginate() function

This function takes a current page and a list of pages. It returns a tuple of previous, next. Both elements of the tuple can be empty.

html() function

This one takes a result of paginate() and returns HTML string for two links. It handles cases when a current page is not found, or either of links is missing.

// List of pages
pages = ['index', 'vanilla', 'ramda', 'elm']

// Previous should be disabled
paginate('index', pages);
// => [undefined, 'vanilla']

html(paginate('index', pages));
// => 'No previous<a href="vanilla">Next</a>'

// Both links are available
html(paginate( 'vanilla', pages));
// => '<a href="index">Previous</a><a href="ramda">Next</a>'

// Non-existent page
html(paginate( 'pageX', pages));
// => 'Current not found'

For the beginning, let’s implement this in vanilla JavaScript.

Continue: Vanilla JavaScript

A random illustration