Skip to content

Instantly share code, notes, and snippets.

@jasonphillips
Last active August 31, 2015 22:01
Show Gist options
  • Save jasonphillips/1306a064a5b0465f56a4 to your computer and use it in GitHub Desktop.
Save jasonphillips/1306a064a5b0465f56a4 to your computer and use it in GitHub Desktop.
Algorithm for finding shortest page for fetching results, given low and high index
/*
* Find smallest page and per_page limit to retrieve a range of results, given low and high
* For non-offset pased paging APIs (where one must send 'per_page' and 'page', rather than offset and limit)
*
* params:
* (integer) low: lowest index to fetch (zero-based)
* (integer) high: highest index to fetch (zero-based)
*
* return value:
* [(integer) per_page, (integer) page]
*
* Example: get page for items 33-39
* getPage(33,39) => [8, 5]
* Fetch page 5, with per_page setting of 8 (will receive indices 32-39)
*/
function getPage(low, high) {
var range = high - low + 1;
if (range < low) {
for (var perpage = range; perpage <= low; perpage++ ) {
if (low % perpage <= perpage - range) {
var offset = Math.floor(low / perpage);
return [perpage, offset + 1];
}
}
} else {
return [high + 1, 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment