Consider this Node.js function that fetches items using cursor-based pagination. What will be the value of nextCursor after fetching the first page?
async function fetchPage(cursor = null) { const pageSize = 3; const allItems = ['a', 'b', 'c', 'd', 'e', 'f']; let startIndex = 0; if (cursor) { startIndex = allItems.indexOf(cursor) + 1; } const pageItems = allItems.slice(startIndex, startIndex + pageSize); const nextCursor = pageItems.length === pageSize ? pageItems[pageItems.length - 1] : null; return { pageItems, nextCursor }; } (async () => { const result = await fetchPage(); console.log(result.nextCursor); })();
Look at how nextCursor is assigned based on the length of pageItems.
The function slices the first 3 items: ['a', 'b', 'c']. Since the page size is 3, nextCursor is set to the last item in the page, which is 'c'.
Given a list of items, which code snippet correctly returns a page of items using offset and limit?
const items = ['x', 'y', 'z', 'w', 'v']; function getPage(offset, limit) { // return a slice of items }
Remember that slice(start, end) uses start inclusive and end exclusive.
Option D correctly slices from offset to offset + limit, returning the correct page.
Examine the following code snippet for cursor pagination. Why might it cause an infinite loop when fetching pages?
async function fetchPages() { let cursor = null; while (true) { const { items, nextCursor } = await fetchPage(cursor); if (!nextCursor) break; cursor = cursor; } }
Check how the cursor variable changes inside the loop.
The code sets cursor = cursor; which does not update the cursor. So the same page is fetched repeatedly, causing an infinite loop.
Choose the best explanation for why cursor-based pagination is often preferred for large datasets.
Think about what happens if data is added or removed while paginating.
Cursor-based pagination uses a stable reference point (cursor) to avoid missing or repeating items if the data changes during pagination.
page after this asynchronous offset pagination loop?Given the following code, what will be the value of page after the loop finishes?
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; const pageSize = 2; let offset = 0; let page = []; async function getPage(offset, limit) { return items.slice(offset, offset + limit); } (async () => { while (true) { page = await getPage(offset, pageSize); if (page.length === 0) break; offset += pageSize; } console.log(page); })();
Consider what happens when the last page is fetched and the loop breaks.
The loop fetches pages of 2 items until no items remain. The last fetch returns an empty array, which breaks the loop. So page is empty at the end.