I'm working in a front-end in which I receive an order from the database and I need to generate a PDF but only wit 10 items per page. I need to generate a list of orders with the same attributes but with 10 items each until the original order items list finishes.
Here an example:
const order = {
name: 'services',
items: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
}
const paginate = (order, pages, start, end) => {
if (order.items.length <= end) {
return pages.concat({
name: order.name,
items: order.items.slice(start, end)
})
} else {
start += 4
end += 4
paginate(order, start, end)
}
}
but that gives me the Maximum call stack size exceeded error. For this example I'm trying to split the order with 3 items. Any help will be really good.
You will need to address some problems in your code like:
pages
parameter in your recursive call which you're not doing.4
for the increment of start
and end
, although you mentioned you want to split the order with 3 items.start <= length of items
.pages
array.pages
array.end
and pages
array.const order = {
name: 'services',
items: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
}
// Time complexity: O(n), n being #of items in the order.items array.
const paginate = (order, itemsPerPage, start = 0, pages = []) => {
// base case
if (start >= order.items.length) {
return pages; // Space Complexity O(n) for pages + depth of call stack used ~ O(n)
}
const end = start + itemsPerPage;
pages.push({
name: order.name,
items: order.items.slice(start, end)
});
return paginate(order, itemsPerPage, end, pages);
}
const paginatedOrders = paginate(order, 3); // <-- update to 4 if you need that
console.log(paginatedOrders);
SIDENOTE:
As you can see it is tail recursive code(and although compilers optimize them behind the scenes), writing iterative approach for it is easier. The asymptotic time and space complexity remains O(n)
although you can save the stack space when you use the iterative approach which in recursive code approximates to (n / itemsPerPage)
.