My goal is to create a pagination algorithm that distributes elements evenly per page, with specified minimum and maximum thresholds. I aim to maximize the number of elements per page while adhering to the minimum rule.
I've attempted to develop my own version of this algorithm but struggle with arranging elements on a page in an aesthetically pleasing way. Below is the code for my test cases:
describe('paginate()', () => {
it('places all elements on one page if less than or equal to maximum', () => {
expect(paginate([1, 2], 1, 8)).toEqual([[1, 2]]);
expect(paginate([1, 2], 3, 8)).toEqual([[1, 2]]);
expect(paginate([1, 2], 1, 2)).toEqual([[1, 2]]);
});
it('divides elements evenly without remainders on max limit', () => {
expect(paginate([1, 2, 3, 4, 5, 6], 1, 3)).toEqual([
[1, 2, 3],
[4, 5, 6],
]);
expect(paginate([1, 2, 3, 4, 5, 6], 1, 2)).toEqual([
[1, 2],
[3, 4],
[5, 6],
]);
});
it('merges last page if there's any leftover elements', () => {
let outcome = paginate([1, 2, 3, 4, 5, 6, 7], 2, 4);
expect(outcome).toEqual([
[1, 2, 3, 4],
[5, 6, 7],
]);
outcome = paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 4);
console.log('outcome', outcome);
expect(outcome).toEqual([
[1, 2, 3, 4],
[5, 6, 7],
[8, 9, 10],
]); // THIS TEST FAILS
});
it('can adjust page sizes to distribute elements evenly', () => {
let outcome = paginate(_.range(1, 12), 6, 10);
expect(outcome).toEqual(
[
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11],
],
JSON.stringify(outcome)
);
outcome = paginate(_.range(1, 22), 6, 10);
expect(outcome).toEqual(
[
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21],
],
JSON.stringify(outcome)
);
});
});
Below is my implementation code:
import _ from 'lodash';
export const paginate = <T>(content: T[], min: number, max: number): T[][] => {
const length = content.length;
for (let i = max; i > min; i--) {
if (length % i === 0 || length % i >= min) {
const result = _.chunk(content, i);
console.log(result);
return result;
}
}
console.log('end');
return _.chunk(content, min);
};
One of my tests is failing, where the output differs from expected. Despite several attempts at solving the issue, it remains unresolved. If anyone has insights on how to make these tests pass or can identify overlooked edge cases, please share your thoughts. I am open to refining the function signature if necessary, such as reconsidering the need for a minimum requirement.