题目
实现 runRequests(events),模拟边输入边搜索时的请求门控。start 事件表示发起新请求,若已有活动请求,则把旧请求 id 记入 aborted 并替换为新的活动请求。complete 事件携带 id 与 value:只有 id 等于当前活动请求时才提交该值并清空活动请求,否则把 id 记入 stale。最终输出按提交顺序排列的 committed 值、aborted 列表与 stale 列表。
解题思路
始终只维护一个 active 标识。处理 start 时,如果 active 不为空,先把它推入 aborted,再用新 id 覆盖。处理 complete 时比较事件 id 与 active:相等就提交 value 并把 active 置空,不相等则说明响应来自已被替代或已经结束的请求,记入 stale。committed 只在提交时追加,因此天然保持完成顺序;aborted 保持被替代的先后顺序。
参考实现要点
active 只能有一个,不能用集合保存多个“活动”请求,否则旧响应仍会被当成有效。提交后必须把 active 清空,这样同一请求的第二个完成事件才会被判为 stale。未完成的请求在新请求到来时立即记为 aborted,而不是等到它自己返回。start 时如果当前没有活动请求,不应产生任何 aborted 记录。
常见错误
把所有 complete 都提交,旧响应会覆盖新结果,出现输入内容与列表不一致。等新请求完成才中止旧请求,中间存在两个请求同时有效的窗口。提交后忘记清空 active,重复完成事件会被重复提交。把未知 id 的完成事件直接忽略而不记入 stale,诊断信息会缺失。
验证方式
逐个运行样例并比对三个数组。补充测试:同一请求重复 complete 只应提交一次,其余记入 stale;在空闲状态发起新请求不应产生 aborted;乱序完成时只有活动请求的值会进入 committed。最后确认 committed 的长度不超过 start 的次数。
代码示例
function runRequests(events) {
let active = null;
const committed = [];
const aborted = [];
const stale = [];
for (const event of events) {
if (event.type === 'start') {
if (active !== null) aborted.push(active);
active = event.id;
} else if (event.type === 'complete') {
if (event.id === active) {
committed.push(event.value);
active = null;
} else {
stale.push(event.id);
}
}
}
return { committed, aborted, stale };
}
const payload = JSON.parse(input);
console.log(JSON.stringify(runRequests(payload.events)));