设计一个操作队列,按时间戳合并冲突。
解读
这道题考察的是**“可预测状态容器”思想在真实业务中的落地能力。
国内中高级前端面试里,Redux 不再只是“写个 reducer 写个 action”那么简单,面试官想看到你对时间序列、冲突消解、幂等性、不可变数据、中间件机制**的综合把控。
核心诉求只有一句话:
“同一业务键、同一时间戳只保留一份有效操作,且整个合并过程必须是纯函数,可回溯、可测试。”
知识点
- 不可变 State 结构
队列本身必须是 Immutable 的(Immer 或手写深复制),否则时间旅行调试直接失效。 - 操作原子化
每个操作描述为{type, payload, meta: {key, ts, idempotentKey}},meta 里带业务主键、毫秒时间戳、幂等令牌。 - 冲突判定策略
国内业务最常见的三种:- 后者覆盖(last-write-wins)
- 业务优先级覆盖(payload 带 priority)
- 自定义合并函数(payload 内嵌 mergeStrategy)
- 纯函数 Reducer
合并逻辑必须无副效应,不能调 Date.now(),不能读 localStorage。 - 中间件拦截
在 action 到达 reducer 之前,用自定义中间件先做“时间窗收集 + 冲突消解”,保证 reducer 收到的已经是干净队列。 - 性能安全
队列长度上限、内存泄漏、O(n²) 去重都要在代码里给出兜底。
答案
以下代码可直接在 Redux 工程跑通,符合国内 Code Review 规范(ESLint + TypeScript 严格模式)。
// types.ts
export interface Op<T = any> {
type: string;
payload: T;
meta: {
key: string; // 业务主键,如订单号
ts: number; // 时间戳,服务端下发,禁止客户端生成
idempotentKey: string;// 幂等令牌,UUID v4
};
}
export interface OpQueueState {
queue: Op[];
index: Record<string, string>; // key -> idempotentKey,用于 O(1) 去重
}
// 初始状态
const initialState: OpQueueState = { queue: [], index: {} };
// 纯函数:按时间戳合并冲突,返回新状态
export function opQueueReducer(
state = initialState,
action: AnyAction
): OpQueueState {
// 只处理带 meta 的 Op
if (!action.meta || !action.meta.key) return state;
const { key, ts, idempotentKey } = action.meta;
const existIdempotent = state.index[key];
// 1. 幂等:已存在且相同令牌直接丢弃
if (existIdempotent === idempotentKey) return state;
// 2. 冲突判定:同一 key,同一时间戳,采用“后者覆盖”策略
const sameTsIndex = state.queue.findIndex(
op => op.meta.key === key && op.meta.ts === ts
);
let nextQueue: Op[];
if (sameTsIndex >= 0) {
// 覆盖旧操作
nextQueue = state.queue.slice();
nextQueue[sameTsIndex] = action as Op;
} else {
// 按时间戳升序插入,保持有序
const insertPos = state.queue.findIndex(op => op.meta.ts > ts);
nextQueue =
insertPos === -1
? [...state.queue, action as Op]
: [
...state.queue.slice(0, insertPos),
action as Op,
...state.queue.slice(insertPos),
];
}
// 3. 更新索引 & 防内存爆炸,队列长度超过 5k 自动裁剪头部
const MAX = 5000;
const trimmed =
nextQueue.length > MAX ? nextQueue.slice(nextQueue.length - MAX) : nextQueue;
const newIndex: Record<string, string> = {};
trimmed.forEach(op => (newIndex[op.meta.key] = op.meta.idempotentKey));
return { queue: trimmed, index: newIndex };
}
// middleware.ts
export const mergeMiddleware: Middleware =
({ getState }) =>
next =>
action => {
// 服务端下发的时间戳必须落在客户端容忍窗口内,防止时钟漂移
if (action.meta) {
const now = Date.now();
const drift = Math.abs(now - action.meta.ts);
if (drift > 30000) {
// 30s 容错,国内网络常见 RTT 上限
console.warn('[merge] 丢弃时钟漂移操作', action);
return; // 直接吞掉,不进 reducer
}
}
return next(action);
};
// 使用
import { configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
reducer: { opQueue: opQueueReducer },
middleware: gDM => gDM().concat(mergeMiddleware),
});
单元测试(Jest)示例,国内面试现场手写能加很多分:
describe('opQueueReducer', () => {
it('同一 key 同一 ts 后者覆盖', () => {
const s1 = opQueueReducer(undefined, {
type: 'ADD',
payload: { v: 1 },
meta: { key: 'A', ts: 100, idempotentKey: 'x' },
});
const s2 = opQueueReducer(s1, {
type: 'ADD',
payload: { v: 2 },
meta: { key: 'A', ts: 100, idempotentKey: 'y' },
});
expect(s2.queue).toHaveLength(1);
expect(s2.queue[0].payload.v).toBe(2);
});
it('幂等相同令牌直接丢弃', () => {
const s1 = opQueueReducer(undefined, {
type: 'ADD',
payload: { v: 1 },
meta: { key: 'A', ts: 100, idempotentKey: 'x' },
});
const s2 = opQueueReducer(s1, {
type: 'ADD',
payload: { v: 99 },
meta: { key: 'A', ts: 100, idempotentKey: 'x' },
});
expect(s2).toBe(s1); // 引用相等,证明纯函数无新对象
});
});
拓展思考
- 分布式场景
如果操作来自多端(小程序、App、Web),时间戳无法保证全局有序,国内常用**“向量时钟 + 服务端最终一致性”**二次校对,此时 Redux 端只需保证“本地视图不冲突、服务端可纠错”即可。 - 可逆回滚
把合并前的旧操作快照放进meta._prev,配合 Redux-Undo 可实现**“撤销重放”**,在飞书、钉钉这类协同文档产品里属于加分项。 - WebWorker 密集计算
当队列长度 >1w 时,冲突合并会阻塞渲染,可把opQueueReducer放进 Comlink 创建的 Worker,通过createAsyncThunk把结果异步写回主线程 Store,保持主线程 60 fps。 - 合规审计
国内金融、医疗项目要求“任何状态变更可审计”,可在中间件里把每次合并前后的队列 diff 序列化成 JSON 片段,通过indexedDB落盘,7 天后自动清理,既满足《个人信息保护法》存储最小化,又能在客诉时快速重放现场。