队列分页实现求助:基于指定参数实现倒序分页逻辑
队列逆序分页(最新数据优先)实现方案
核心逻辑
队列遵循0索引为最旧数据,末尾索引为最新数据的规则,分页要求:
- 第1页返回最新的
limit条记录,通过计算起始偏移量从总长度 - limit开始读取到队列末尾 - 第2页及以后返回剩余的旧数据,从最旧的记录开始,每页取
limit条,直到数据耗尽
伪代码
function getPaginatedQueue(queue, page, limit) { total = length of queue if total == 0: return empty array if page == 1: // 计算第一页起始偏移,确保不小于0(当总长度小于limit时从0开始) start = max(0, total - limit) // 取从start到末尾的所有元素 return queue[start ... total-1] else: // 第一页取完后剩余的旧数据条数 remaining = total - min(total, limit) if remaining == 0: return empty array // 计算当前页的起始偏移(第2页从0开始,第3页从limit开始,以此类推) start = (page - 2) * limit if start >= remaining: return empty array // 计算当前页的结束偏移,不超过剩余数据的最后索引 end = min(start + limit - 1, remaining - 1) return queue[start ... end] }
JavaScript 实现
function getPaginatedQueue(queue, page, limit) { const total = queue.length; if (total === 0) return []; // 处理第一页:取最新的limit条 if (page === 1) { const start = Math.max(0, total - limit); return queue.slice(start); // slice(start) 等价于 slice(start, total) } // 处理第2页及以后:取剩余的旧数据 const remaining = total - Math.min(total, limit); if (remaining === 0) return []; const start = (page - 2) * limit; if (start >= remaining) return []; const end = Math.min(start + limit, remaining); return queue.slice(start, end); }
测试示例
示例1:12条记录的队列,每页10条
// 模拟队列:record-0(最旧)到 record-11(最新) const queue1 = Array.from({ length: 12 }, (_, idx) => `record-${idx}`); console.log(getPaginatedQueue(queue1, 1, 10)); // 输出:["record-2", "record-3", ..., "record-11"](共10条最新记录) console.log(getPaginatedQueue(queue1, 2, 10)); // 输出:["record-0", "record-1"](剩余2条旧记录) console.log(getPaginatedQueue(queue1, 3, 10)); // 输出:[](无更多数据)
示例2:15条记录的队列(偏移0-14),每页10条
const queue2 = Array.from({ length: 15 }, (_, idx) => `record-${idx}`); console.log(getPaginatedQueue(queue2, 1, 10)); // 输出:["record-5", "record-6", ..., "record-14"](10条最新记录) console.log(getPaginatedQueue(queue2, 2, 10)); // 输出:["record-0", "record-1", ..., "record-4"](剩余5条旧记录)
内容的提问来源于stack exchange,提问作者Hari Krishnan Ramachandran
相关产品推荐
相关产品推荐

