JSFiddle - React, Tailwind, and code Playground
by burki
JavaScript
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
class Slicer {
/**
* A Slicer subdivides an array [0...n] into disjunct pages,
* each page not containing more than maxPageSize elements.
*
* @param {number} n
* @param {number} maxPageSize
*/
constructor(n, maxPageSize) {
assert(n >= 0, "max:" + n + " is < 0");
assert(maxPageSize > 0, "maxPageSize: " + maxPageSize + " is <= 0");
this.n = n;
this.maxPageSize = maxPageSize;
this.maxPage = Math.trunc(n / maxPageSize);
}
/**
* Retrieves the given page.
*
* @param {number} page
* @returns {[number]}
*/
getPage(page) {
assert(
0 <= page && page <= this.maxPage,
"page: " + page + " is < 0 or > " + this.maxPage
);
if (this.maxPage === 0) {
// return [...Array(this.n + 1).keys()]; // shorter, faster?
const values = [];
for (let i = this.n; i >= 0; --i) {
values.push(i);
}
return values;
}
const add = this.maxPage + 1;
let count = Math.trunc((this.n - page) / add) + 1;
console.info("count", count)
console.info("this.maxPageSize", this.maxPageSize)
const flag = count < this.maxPageSize;
const values = [];
let inc = 0;
while (--count >= 0) {
let value = page;
if (count > 0 || flag) {
console.info("rotate")
value += 1;
value = value % add;
}
value += inc;
values.push(value);
inc += add;
}
//for (let i = page; i <= this.n; i += add) {
//values.push(i);
//--count;
//}
//assert(count === 0, "mathematics is broken"); // should never happen ;-)
return values;
}
}
const s = new Slicer(9, 4);
for (let p = 0; p <= s.maxPage; ++p) {
console.info(s.getPage(p));
}