You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

队列分页实现求助:基于指定参数实现倒序分页逻辑

队列逆序分页(最新数据优先)实现方案

核心逻辑

队列遵循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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:55:28