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.
2
Answers
it’s like this?
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 ofstart
andend
, although you mentioned you want to split the order with 3 items.My approach:
start <= length of items
.1.1. If yes, return the
pages
array.pages
array.end
andpages
array.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)
.