Last active
August 31, 2015 22:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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