Skip to content

Instantly share code, notes, and snippets.

@davidgarsan
Last active August 8, 2018 06:12
Show Gist options
  • Save davidgarsan/4d2768d6eac122d164b57d3945b20230 to your computer and use it in GitHub Desktop.
Save davidgarsan/4d2768d6eac122d164b57d3945b20230 to your computer and use it in GitHub Desktop.
Infinite Array Pagination
/**
* Takes an array, a given window size and
* a starting index and returns a fragment of the
* array with infinite pagination.
* If the window size if bigger than teh array size,
* it shouldn't be paginated.
**/
const a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
function infinitePagination(index, size, array) {
// Limit index to availables in length.
const i = index % array.length;
// Limit size to avoid showing duplicated items.
const l = Math.min(size - 1, array.length -1);
const c = array.length - l;
const frag1 = array.slice(array.length + i - 1, array.length);
const frag2 = array.slice(i - 1, i);
const frag3 = array.slice(i, i + l);
const frag4 = array.slice(0, Math.max(0, i - c));
return [...frag1, ...frag2, ...frag3, ...frag4];
}
const width = 7;
console.log(infinitePagination(0, width, a)); // [11, 0, 1, 2, 3, 4, 5]
console.log(infinitePagination(1, width, a)); // [0, 1, 2, 3, 4, 5, 6]
console.log(infinitePagination(2, width, a)); // [1, 2, 3, 4, 5, 6, 7]
console.log(infinitePagination(3, width, a)); // [2, 3, 4, 5, 6, 7, 8]
console.log(infinitePagination(4, width, a)); // [3, 4, 5, 6, 7, 8, 9]
console.log(infinitePagination(5, width, a)); // [4, 5, 6, 7, 8, 9, 10]
console.log(infinitePagination(6, width, a)); // [5, 6, 7, 8, 9, 10, 11]
console.log(infinitePagination(7, width, a)); // [6, 7, 8, 9, 10, 11, 0]
console.log(infinitePagination(8, width, a)); // [7, 8, 9, 10, 11, 0, 1]
console.log(infinitePagination(9, width, a)); // [8, 9, 10, 11, 0, 1, 2]
console.log(infinitePagination(10, width, a)); // [9, 10, 11, 0, 1, 2, 3]
console.log(infinitePagination(11, width, a)); // [10, 11, 0, 1, 2, 3, 4]
console.log(infinitePagination(12, width, a)); // [11, 0, 1, 2, 3, 4, 5]
console.log(infinitePagination(13, width, a)); // [0, 1, 2, 3, 4, 5, 6]
console.log(infinitePagination(14, width, a)); // [1, 2, 3, 4, 5, 6, 7]
console.log(infinitePagination(15, width, a)); // [2, 3, 4, 5, 6, 7, 8]
console.log(infinitePagination(16, width, a)); // [3, 4, 5, 6, 7, 8, 9]
console.log(infinitePagination(17, width, a)); // [4, 5, 6, 7, 8, 9, 10]
console.log(infinitePagination(18, width, a)); // [5, 6, 7, 8, 9, 10, 11]
console.log(infinitePagination(19, width, a)); // [6, 7, 8, 9, 10, 11, 0]
console.log(infinitePagination(20, width, a)); // [7, 8, 9, 10, 11, 0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment